#include "stdafx.h"

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#include <limits.h>
#include <assert.h>

#ifndef NO_MULTIMON
#define COMPILE_MULTIMON_STUBS
#endif
#include "sshterm.h"
#include "terminal.h"

#ifndef NO_MULTIMON
#include <multimon.h>
#endif

#include <imm.h>
#include <commctrl.h>
#include <richedit.h>
#include <mmsystem.h>

#include "window.h"
#include "ldisc.h"


#define WM_IGNORE_CLIP (WM_APP + 2)
#define WM_FULLSCR_ON_MAX (WM_APP + 3)

OSVERSIONINFO osVersion;


/* Needed for Chinese support and apparently not always defined. */
#ifndef VK_PROCESSKEY
#define VK_PROCESSKEY 0xE5
#endif

/* Mouse wheel support. */
#ifndef WM_MOUSEWHEEL
#define WM_MOUSEWHEEL 0x020A	       /* not defined in earlier SDKs */
#endif
#ifndef WHEEL_DELTA
#define WHEEL_DELTA 120
#endif


 
void force_normal(HWND hwnd)
{
    static int recurse = 0;

    WINDOWPLACEMENT wp;

    if (recurse)
	return;
    recurse = 1;

    wp.length = sizeof(wp);
    if (GetWindowPlacement(hwnd, &wp) && wp.showCmd == SW_SHOWMAXIMIZED) {
	wp.showCmd = SW_SHOWNORMAL;
	SetWindowPlacement(hwnd, &wp);
    }
    recurse = 0;
}

#define TIMING_TIMER_ID 1234


char *dupvprintf(const char *fmt, va_list ap)
{
    char *buf;
    int len, size;

    buf = memallocn(512, char);
    size = 512;

    while (1) {
#ifdef _WINDOWS
#define vsnprintf _vsnprintf
#endif
#ifdef va_copy
	/* Use the `va_copy' macro mandated by C99, if present.
	 * XXX some environments may have this as __va_copy() */
	va_list aq;
	va_copy(aq, ap);
	len = vsnprintf(buf, size, fmt, aq);
	va_end(aq);
#else
	/* Ugh. No va_copy macro, so do something nasty.
	 * Technically, you can't reuse a va_list like this: it is left
	 * unspecified whether advancing a va_list pointer modifies its
	 * value or something it points to, so on some platforms calling
	 * vsnprintf twice on the same va_list might fail hideously
	 * (indeed, it has been observed to).
	 * XXX the autoconf manual suggests that using memcpy() will give
	 *     "maximum portability". */
	len = _vsnprintf(buf, size, fmt, ap);
#endif
	if (len >= 0 && len < size) {
	    /* This is the C99-specified criterion for snprintf to have
	     * been completely successful. */
	    return buf;
	} else if (len > 0) {
	    /* This is the C99 error condition: the returned length is
	     * the required buffer size not counting the NUL. */
	    size = len + 1;
	} else {
	    /* This is the pre-C99 glibc error condition: <0 means the
	     * buffer wasn't big enough, so we enlarge it a bit and hope. */
	    size += 512;
	}
	buf = memrealloc(buf, size, char);
    }
}

char *get_ttymode(SshWindow wnd, const char *mode)
{
    return term_get_ttymode(wnd->term, mode);
}

static void close_session(SshWindow wnd)
{
    char morestuff[100];
    deinit_fonts(wnd);
    memfree(wnd->logpal);
    if (wnd->pal)
	DeleteObject(wnd->pal);

    wnd->session_closed = TRUE;
    sprintf(morestuff, "(inactive)");
    set_icon(NULL, morestuff);
    set_title(NULL, morestuff);

    if (wnd->ldisc) {
	ldisc_free(wnd->ldisc);
	wnd->ldisc = NULL;
    }
    if (wnd->back) {
        term_provide_resize_fn(wnd->term, NULL, NULL);
    }

}

/*	init function. prepares window and frontend for output */

SshWindow init(Backend *back, HWND hwnd, Config cfg) {
    int guess_width, guess_height;

	if (!IsWindow(hwnd)) return NULL;

	SshWindow wnd = memalloc(window_tag);
	memset(wnd,0,sizeof(window_tag));
	wnd->caret_x = -1;
	wnd->caret_y = -1;
	wnd->back = back;
	wnd->hwnd = hwnd;
	wnd->wm_mousewheel = WM_MOUSEWHEEL;
	memcpy(&wnd->cfg,&cfg,sizeof(term_config_tag));

    cfgtopalette(wnd);

	wnd->font_width = 10;
    wnd->font_height = 20;
    wnd->extra_width = 25;
    wnd->extra_height = 28;
    guess_width = wnd->extra_width + wnd->font_width * wnd->cfg.cfg->width;
    guess_height = wnd->extra_height + wnd->font_height * wnd->cfg.cfg->height;
    {
	RECT r;
		get_fullscreen_rect(wnd,&r);
	if (guess_width > r.right - r.left)
	    guess_width = r.right - r.left;
	if (guess_height > r.bottom - r.top)
	    guess_height = r.bottom - r.top;
    }


    /*
     * Initialise the fonts, simultaneously correcting the guesses
     * for font_{width,height}.
     */
    init_fonts(wnd, 0,0);
	wnd->term = term_init(&wnd->cfg, &wnd->ucsdata, wnd);
	term_size(wnd->term, cfg.cfg->height, cfg.cfg->width, cfg.savelines);

	RECT cr, wr;
    /*
     * Correct the guesses for extra_{width,height}.
     */
    {
	GetWindowRect(hwnd, &wr);
	GetClientRect(hwnd, &cr);
	wnd->offset_width = wnd->offset_height = wnd->cfg.window_border;
	wnd->extra_width = wr.right - wr.left - cr.right + cr.left + wnd->offset_width*2;
	wnd->extra_height = wr.bottom - wr.top - cr.bottom + cr.top +wnd->offset_height*2;
    }

    /*
     * Resize the window, now we know what size we _really_ want it
     * to be.
     */
    guess_width = wnd->extra_width + wnd->font_width * wnd->term->cols;
    guess_height = wnd->extra_height + wnd->font_height * wnd->term->rows;
	SetWindowPos(hwnd, NULL, wr.left, wr.top, guess_width, guess_height,
		 0);


    /*
     * Set up a caret bitmap, with no content.
     */
    {
	char *bits;
	int size = (wnd->font_width + 15) / 16 * 2 * wnd->font_height;
	bits = memallocn(size, char);
	memset(bits, 0, size);
	wnd->caretbm = CreateBitmap(wnd->font_width, wnd->font_height, 1, 1, bits);
	memfree(bits);
    }
    CreateCaret(hwnd, wnd->caretbm, wnd->font_width, wnd->font_height);

    /*
     * Initialise the scroll bar.
     */
    {
	SCROLLINFO si;

	si.cbSize = sizeof(si);
	si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
	si.nMin = 0;
	si.nMax = wnd->term->rows - 1;
	si.nPage = wnd->term->rows;
	si.nPos = 0;
	SetScrollInfo(hwnd, SB_VERT, &si, FALSE);
    }
    /*
     * Prepare the mouse handler.
     */
    wnd->lastact = MA_NOTHING;
    wnd->lastbtn = MBT_NOTHING;
    wnd->dbltime = GetDoubleClickTime();

    /*
     * Set up the initial input locale.
     */
    set_input_locale(wnd, GetKeyboardLayout(0));

    /*
     * Set the palette up.
     */
    wnd->pal = NULL;
    wnd->logpal = NULL;
    init_palette(wnd);

    term_set_focus(wnd->term, GetForegroundWindow() == hwnd);
    UpdateWindow(hwnd);
	return wnd;
}

void start_session(SshWindow wnd, int localid, void *backhandle)
{
    char msg[1024], *title;
	if (!wnd || !backhandle) return;

	wnd->localid = localid;
	wnd->backhandle = backhandle;

	SECURITY_ATTRIBUTES s_attrs;
	s_attrs.nLength=sizeof(SECURITY_ATTRIBUTES);
	s_attrs.bInheritHandle=TRUE;
	s_attrs.lpSecurityDescriptor=NULL;

	wnd->evt=CreateEvent(&s_attrs,FALSE,TRUE,NULL);


    wnd->window_name = wnd->icon_name = NULL;
    if (*wnd->cfg.wintitle) {
	title = wnd->cfg.wintitle;
    } else {
		sprintf(msg, "%s", wnd->cfg.cfg->host);
		title = msg;
    }

	set_title(wnd, title);
    set_icon(wnd, title);

    /*
     * Connect the terminal to the backend for resize purposes.
     */
    term_provide_resize_fn(wnd->term, wnd->back->size, backhandle);

    /*
     * Set up a line discipline.
     */
	wnd->ldisc = ldisc_create(&wnd->cfg, wnd->term, wnd->back, backhandle);

    wnd->must_close_session = FALSE;
    wnd->session_closed = FALSE;
}

static void update_mouse_pointer(SshWindow wnd)
{
    LPTSTR curstype;
    int force_visible = FALSE;
    static int forced_visible = FALSE;
    switch (wnd->busy_status) {
      case BUSY_NOT:
	if (wnd->send_raw_mouse)
	    curstype = IDC_ARROW;
	else
	    curstype = IDC_IBEAM;
	break;
      case BUSY_WAITING:
	curstype = IDC_APPSTARTING; /* this may be an abuse */
	force_visible = TRUE;
	break;
      case BUSY_CPU:
	curstype = IDC_WAIT;
	force_visible = TRUE;
	break;
      default:
	assert(0);
    }
    {
	HCURSOR cursor = LoadCursor(NULL, curstype);
	SetClassLongPtr(wnd->hwnd, GCLP_HCURSOR, (LONG_PTR)cursor);
	SetCursor(cursor); /* force redraw of cursor at current posn */
    }
    if (force_visible != forced_visible) {
	/* We want some cursor shapes to be visible always.
	 * Along with show_mouseptr(), this manages the ShowCursor()
	 * counter such that if we switch back to a non-force_visible
	 * cursor, the previous visibility state is restored. */
	ShowCursor(force_visible);
	forced_visible = force_visible;
    }
}

void set_busy_status(SshWindow wnd, int status)
{
    wnd->busy_status = status;
    update_mouse_pointer(wnd);
}

/*
 * set or clear the "raw mouse message" mode
 */
void set_raw_mouse_mode(SshWindow wnd, int activate)
{
	activate = activate && !wnd->cfg.no_mouse_rep;
    wnd->send_raw_mouse = activate;
    update_mouse_pointer(wnd);
}

/*
 * Print a message box and close the connection.
 */
void connection_fatal(SshWindow wnd, char *fmt, ...)
{
    va_list ap;
    char *stuff, morestuff[100];

    va_start(ap, fmt);
    stuff = dupvprintf(fmt, ap);
    va_end(ap);
    sprintf(morestuff, "Fatal Error");
    MessageBoxA(wnd->hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
    memfree(stuff);

    if (wnd->cfg.cfg->close_on_exit == FORCE_ON)
	PostQuitMessage(1);
    else {
	wnd->must_close_session = TRUE;
    }
}

/*
 * Copy the colour palette from the configuration data into wnd->defpal.
 * This is non-trivial because the colour indices are different.
 */
static void cfgtopalette(SshWindow wnd)
{
    int i;
    static const int ww[] = {
	256, 257, 258, 259, 260, 261,
	0, 8, 1, 9, 2, 10, 3, 11,
	4, 12, 5, 13, 6, 14, 7, 15
    };

    for (i = 0; i < 22; i++) {
	int w = ww[i];
	wnd->defpal[w].rgbtRed = wnd->cfg.colours[i][0];
	wnd->defpal[w].rgbtGreen = wnd->cfg.colours[i][1];
	wnd->defpal[w].rgbtBlue = wnd->cfg.colours[i][2];
    }
    for (i = 0; i < NEXTCOLOURS; i++) {
	if (i < 216) {
	    int r = i / 36, g = (i / 6) % 6, b = i % 6;
	    wnd->defpal[i+16].rgbtRed = r ? r * 40 + 55 : 0;
	    wnd->defpal[i+16].rgbtGreen = g ? g * 40 + 55 : 0;
	    wnd->defpal[i+16].rgbtBlue = b ? b * 40 + 55 : 0;
	} else {
	    int shade = i - 216;
	    shade = shade * 10 + 8;
	    wnd->defpal[i+16].rgbtRed = wnd->defpal[i+16].rgbtGreen =
		wnd->defpal[i+16].rgbtBlue = shade;
	}
    }

    /* Override with system wnd->colours if appropriate */
    if (wnd->cfg.system_colour)
        systopalette(wnd);
}

/*
 * Override bit of wnd->defpal with wnd->colours from the system.
 * (NB that this takes a copy the system wnd->colours at the time this is called,
 * so subsequent colour scheme changes don't take effect. To fix that we'd
 * probably want to be using GetSysColorBrush() and the like.)
 */
static void systopalette(SshWindow wnd)
{
    int i;
    static const struct { int nIndex; int norm; int bold; } or[] =
    {
	{ COLOR_WINDOWTEXT,	256, 257 }, /* Default Foreground */
	{ COLOR_WINDOW,		258, 259 }, /* Default Background */
	{ COLOR_HIGHLIGHTTEXT,	260, 260 }, /* Cursor Text */
	{ COLOR_HIGHLIGHT,	261, 261 }, /* Cursor Colour */
    };

    for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {
	COLORREF colour = GetSysColor(or[i].nIndex);
	wnd->defpal[or[i].norm].rgbtRed =
	   wnd->defpal[or[i].bold].rgbtRed = GetRValue(colour);
	wnd->defpal[or[i].norm].rgbtGreen =
	   wnd->defpal[or[i].bold].rgbtGreen = GetGValue(colour);
	wnd->defpal[or[i].norm].rgbtBlue =
	   wnd->defpal[or[i].bold].rgbtBlue = GetBValue(colour);
    }
}

/*
 * Set up the colour palette.
 */
static void init_palette(SshWindow wnd)
{
    int i;
    HDC hdc = GetDC(wnd->hwnd);
    if (hdc) {
	if (wnd->cfg.try_palette && GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
	    /*
	     * This is a genuine case where we must use memalloc
	     * because the memalloc macros can't cope.
	     */
	    wnd->logpal = (LPLOGPALETTE)malloc(sizeof(LPLOGPALETTE)
			     - sizeof(wnd->logpal->palPalEntry)
			     + NALLCOLOURS * sizeof(PALETTEENTRY));
	    wnd->logpal->palVersion = 0x300;
	    wnd->logpal->palNumEntries = NALLCOLOURS;
	    for (i = 0; i < NALLCOLOURS; i++) {
		wnd->logpal->palPalEntry[i].peRed = wnd->defpal[i].rgbtRed;
		wnd->logpal->palPalEntry[i].peGreen = wnd->defpal[i].rgbtGreen;
		wnd->logpal->palPalEntry[i].peBlue = wnd->defpal[i].rgbtBlue;
		wnd->logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
	    }
	    wnd->pal = CreatePalette(wnd->logpal);
	    if (wnd->pal) {
		SelectPalette(hdc, wnd->pal, FALSE);
		RealizePalette(hdc);
		SelectPalette(hdc, (HPALETTE)GetStockObject(DEFAULT_PALETTE), FALSE);
	    }
	}
	ReleaseDC(wnd->hwnd, hdc);
    }
    if (wnd->pal)
	for (i = 0; i < NALLCOLOURS; i++)
	    wnd->colours[i] = PALETTERGB(wnd->defpal[i].rgbtRed,
				    wnd->defpal[i].rgbtGreen,
				    wnd->defpal[i].rgbtBlue);
    else
	for (i = 0; i < NALLCOLOURS; i++)
	    wnd->colours[i] = RGB(wnd->defpal[i].rgbtRed,
			     wnd->defpal[i].rgbtGreen, wnd->defpal[i].rgbtBlue);
}

/*
 * This is a wrapper to ExtTextOut() to force Windows to display
 * the precise glyphs we give it. Otherwise it would do its own
 * bidi and Arabic shaping, and we would end up uncertain which
 * characters it had put where.
 */
static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
			  wchar_t *lpString, UINT cbCount,
			  CONST INT *lpDx, int opaque)
{
#ifdef __LCC__
    /*
     * The LCC include files apparently don't supply the
     * GCP_RESULTSW type, but we can make do with GCP_RESULTS
     * proper: the differences aren't important to us (the only
     * variable-width string parameter is one we don't use anyway).
     */
    GCP_RESULTS gcpr;
#else
    GCP_RESULTSW gcpr;
#endif
    char *buffer = memallocn(cbCount*2+2, char);
    char *classbuffer = memallocn(cbCount, char);
    memset(&gcpr, 0, sizeof(gcpr));
    memset(buffer, 0, cbCount*2+2);
    memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);

    gcpr.lStructSize = sizeof(gcpr);
    gcpr.lpGlyphs = (LPWSTR)buffer;
    gcpr.lpClass = (LPSTR)classbuffer;
    gcpr.nGlyphs = cbCount;

    GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
			   FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);

    ExtTextOutA(hdc, x, y,
	       ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
	       lprc, buffer, cbCount, lpDx);
}

/*
 * The exact_textout() wrapper, unfortunately, destroys the useful
 * Windows `font linking' behaviour: automatic handling of Unicode
 * code points not supported in this font by falling back to a font
 * which does contain them. Therefore, we adopt a multi-layered
 * approach: for any potentially-bidi text, we use exact_textout(),
 * and for everything else we use a simple ExtTextOut as we did
 * before exact_textout() was introduced.
 */
static void general_textout(HDC hdc, int x, int y, CONST RECT *lprc,
			    wchar_t *lpString, UINT cbCount,
			    CONST INT *lpDx, int opaque)
{
    int i, j, xp, xn;
    RECT newrc;

#ifdef FIXME_REMOVE_BEFORE_CHECKIN
int k;
debug(("general_textout: %d,%d", x, y));
for(k=0;k<cbCount;k++)debug((" U+%04X", lpString[k]));
debug(("\n           rect: [%d,%d %d,%d]", lprc->left, lprc->top, lprc->right, lprc->bottom));
debug(("\n"));
#endif

    xp = xn = x;

    for (i = 0; i < (int)cbCount ;) {
	int rtl = is_rtl(lpString[i]);

	xn += lpDx[i];

	for (j = i+1; j < (int)cbCount; j++) {
	    if (rtl != is_rtl(lpString[j]))
		break;
	    xn += lpDx[j];
	}

	/*
	 * Now [i,j) indicates a maximal substring of lpString
	 * which should be displayed using the same textout
	 * function.
	 */
	if (rtl) {
	    newrc.left = lprc->left + xp - x;
	    newrc.right = lprc->left + xn - x;
	    newrc.top = lprc->top;
	    newrc.bottom = lprc->bottom;
#ifdef FIXME_REMOVE_BEFORE_CHECKIN
{
int k;
debug(("  exact_textout: %d,%d", xp, y));
for(k=0;k<j-i;k++)debug((" U+%04X", lpString[i+k]));
debug(("\n           rect: [%d,%d %d,%d]\n", newrc.left, newrc.top, newrc.right, newrc.bottom));
}
#endif
	    exact_textout(hdc, xp, y, &newrc, lpString+i, j-i, lpDx+i, opaque);
	} else {
#ifdef FIXME_REMOVE_BEFORE_CHECKIN
{
int k;
debug(("  ExtTextOut   : %d,%d", xp, y));
for(k=0;k<j-i;k++)debug((" U+%04X", lpString[i+k]));
debug(("\n           rect: [%d,%d %d,%d]\n", newrc.left, newrc.top, newrc.right, newrc.bottom));
}
#endif
	    newrc.left = lprc->left + xp - x;
	    newrc.right = lprc->left + xn - x;
	    newrc.top = lprc->top;
	    newrc.bottom = lprc->bottom;
	    ExtTextOutW(hdc, xp, y, ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
			&newrc, lpString+i, j-i, lpDx+i);
	}

	i = j;
	xp = xn;
    }

#ifdef FIXME_REMOVE_BEFORE_CHECKIN
debug(("general_textout: done, xn=%d\n", xn));
#endif
    assert(xn - x == lprc->right - lprc->left);
}

/*
 * Initialise all the fonts we will need initially. There may be as many as
 * three or as few as one.  The other (poentially) twentyone fonts are done
 * if/when they are needed.
 *
 * We also:
 *
 * - check the font width and height, correcting our guesses if
 *   necessary.
 *
 * - verify that the bold font is the same width as the ordinary
 *   one, and engage shadow bolding if not.
 * 
 * - verify that the underlined font is the same width as the
 *   ordinary one (manual underlining by means of line drawing can
 *   be done in a pinch).
 */
static void init_fonts(SshWindow wnd, int pick_width, int pick_height)
{
    TEXTMETRIC tm;
    CPINFO cpinfo;
    int fontsize[3];
    int i;
    HDC hdc;
    int fw_dontcare, fw_bold;

    for (i = 0; i < FONT_MAXNO; i++)
	wnd->fonts[i] = NULL;

	wnd->bold_mode = wnd->cfg.bold_colour ? window_tag::BOLD_COLOURS : window_tag::BOLD_FONT;
    wnd->und_mode = window_tag::UND_FONT;

    if (wnd->cfg.font.isbold) {
	fw_dontcare = FW_BOLD;
	fw_bold = FW_HEAVY;
    } else {
	fw_dontcare = FW_DONTCARE;
	fw_bold = FW_BOLD;
    }

    hdc = GetDC(wnd->hwnd);

    if (pick_height)
	wnd->font_height = pick_height;
    else {
	wnd->font_height = wnd->cfg.font.height;
	if (wnd->font_height > 0) {
	    wnd->font_height =
		-MulDiv(wnd->font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
	}
    }
    wnd->font_width = pick_width;

#define f(i,c,w,u) \
    wnd->fonts[i] = CreateFontA(wnd->font_height, wnd->font_width, 0, 0, w, FALSE, u, FALSE, \
			   c, OUT_DEFAULT_PRECIS, \
		           CLIP_DEFAULT_PRECIS, FONT_QUALITY(wnd->cfg.font_quality), \
			   FIXED_PITCH | FF_DONTCARE, wnd->cfg.font.name)

    f(FONT_NORMAL, wnd->cfg.font.charset, fw_dontcare, FALSE);

    SelectObject(hdc, wnd->fonts[FONT_NORMAL]);
    GetTextMetrics(hdc, &tm);

    GetObject(wnd->fonts[FONT_NORMAL], sizeof(LOGFONT), &wnd->lfont);

    if (pick_width == 0 || pick_height == 0) {
	wnd->font_height = tm.tmHeight;
	wnd->font_width = tm.tmAveCharWidth;
    }
    wnd->font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);

#ifdef RDB_DEBUG_PATCH
    debug(23, "Primary font H=%d, AW=%d, MW=%d",
	    tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
#endif

    {
	CHARSETINFO info;
	DWORD cset = tm.tmCharSet;
	memset(&info, 0xFF, sizeof(info));

	/* !!! Yes the next line is right */
	if (cset == OEM_CHARSET)
	    wnd->ucsdata.font_codepage = GetOEMCP();
	else
	    if (TranslateCharsetInfo ((DWORD *) cset, &info, TCI_SRCCHARSET))
		wnd->ucsdata.font_codepage = info.ciACP;
	else
	    wnd->ucsdata.font_codepage = -1;

	GetCPInfo(wnd->ucsdata.font_codepage, &cpinfo);
	wnd->ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
    }

    f(FONT_UNDERLINE, wnd->cfg.font.charset, fw_dontcare, TRUE);

    /*
     * Some fonts, e.g. 9-pt Courier, draw their underlines
     * outside their character cell. We successfully prevent
     * screen corruption by clipping the text output, but then
     * we lose the underline completely. Here we try to work
     * out whether this is such a font, and if it is, we set a
     * flag that causes underlines to be drawn by hand.
     *
     * Having tried other more sophisticated approaches (such
     * as examining the TEXTMETRIC structure or requesting the
     * height of a string), I think we'll do this the brute
     * force way: we create a small bitmap, draw an underlined
     * space on it, and test to see whether any pixels are
     * foreground-coloured. (Since we expect the underline to
     * go all the way across the character cell, we only search
     * down a single column of the bitmap, half way across.)
     */
    {
	HDC und_dc;
	HBITMAP und_bm, und_oldbm;
	int i, gotit;
	COLORREF c;

	und_dc = CreateCompatibleDC(hdc);
	und_bm = CreateCompatibleBitmap(hdc, wnd->font_width, wnd->font_height);
	und_oldbm = (HBITMAP)SelectObject(und_dc, und_bm);
	SelectObject(und_dc, wnd->fonts[FONT_UNDERLINE]);
	SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
	SetTextColor(und_dc, RGB(255, 255, 255));
	SetBkColor(und_dc, RGB(0, 0, 0));
	SetBkMode(und_dc, OPAQUE);
	ExtTextOutA(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
	gotit = FALSE;
	for (i = 0; i < wnd->font_height; i++) {
	    c = GetPixel(und_dc, wnd->font_width / 2, i);
	    if (c != RGB(0, 0, 0))
		gotit = TRUE;
	}
	SelectObject(und_dc, und_oldbm);
	DeleteObject(und_bm);
	DeleteDC(und_dc);
	if (!gotit) {
		wnd->und_mode = window_tag::UND_LINE;
	    DeleteObject(wnd->fonts[FONT_UNDERLINE]);
	    wnd->fonts[FONT_UNDERLINE] = 0;
	}
    }

    if (wnd->bold_mode == window_tag::BOLD_FONT) {
	f(FONT_BOLD, wnd->cfg.font.charset, fw_bold, FALSE);
    }
#undef f

    wnd->descent = tm.tmAscent + 1;
    if (wnd->descent >= wnd->font_height)
	wnd->descent = wnd->font_height - 1;

    for (i = 0; i < 3; i++) {
	if (wnd->fonts[i]) {
	    if (SelectObject(hdc, wnd->fonts[i]) && GetTextMetrics(hdc, &tm))
		fontsize[i] = tm.tmAveCharWidth + 256 * tm.tmHeight;
	    else
		fontsize[i] = -i;
	} else
	    fontsize[i] = -i;
    }

    ReleaseDC(wnd->hwnd, hdc);

    if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
		wnd->und_mode = window_tag::UND_LINE;
	DeleteObject(wnd->fonts[FONT_UNDERLINE]);
	wnd->fonts[FONT_UNDERLINE] = 0;
    }

    if (wnd->bold_mode == window_tag::BOLD_FONT &&
	fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
	wnd->bold_mode = window_tag::BOLD_SHADOW;
	DeleteObject(wnd->fonts[FONT_BOLD]);
	wnd->fonts[FONT_BOLD] = 0;
    }
    wnd->fontflag[0] = wnd->fontflag[1] = wnd->fontflag[2] = 1;

    init_ucs(&wnd->cfg, &wnd->ucsdata);
}

static void another_font(SshWindow wnd, int fontno)
{
    int basefont;
    int fw_dontcare, fw_bold;
    int c, u, w, x;
    char *s;

    if (fontno < 0 || fontno >= FONT_MAXNO || wnd->fontflag[fontno])
	return;

    basefont = (fontno & ~(FONT_BOLDUND));
    if (basefont != fontno && !wnd->fontflag[basefont])
	another_font(wnd, basefont);

    if (wnd->cfg.font.isbold) {
	fw_dontcare = FW_BOLD;
	fw_bold = FW_HEAVY;
    } else {
	fw_dontcare = FW_DONTCARE;
	fw_bold = FW_BOLD;
    }

    c = wnd->cfg.font.charset;
    w = fw_dontcare;
    u = FALSE;
    s = wnd->cfg.font.name;
    x = wnd->font_width;

    if (fontno & FONT_WIDE)
	x *= 2;
    if (fontno & FONT_NARROW)
	x = (x+1)/2;
    if (fontno & FONT_OEM)
	c = OEM_CHARSET;
    if (fontno & FONT_BOLD)
	w = fw_bold;
    if (fontno & FONT_UNDERLINE)
	u = TRUE;

    wnd->fonts[fontno] =
	CreateFontA(wnd->font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
		   FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
		   CLIP_DEFAULT_PRECIS, FONT_QUALITY(wnd->cfg.font_quality),
		   FIXED_PITCH | FF_DONTCARE, s);

    wnd->fontflag[fontno] = 1;
}

static void deinit_fonts(SshWindow wnd)
{
    int i;
    for (i = 0; i < FONT_MAXNO; i++) {
	if (wnd->fonts[i])
	    DeleteObject(wnd->fonts[i]);
	wnd->fonts[i] = 0;
	wnd->fontflag[i] = 0;
    }
}

void request_resize(SshWindow wnd, int w, int h)
{
    int width, height;

    /* If the window is maximized supress resizing attempts */
    if (IsZoomed(wnd->hwnd)) {
	if (wnd->cfg.resize_action == RESIZE_TERM)
	    return;
    }

    if (wnd->cfg.resize_action == RESIZE_DISABLED) return;
    if (h == wnd->term->rows && w == wnd->term->cols) return;

    /* Sanity checks ... */
    {
	static int first_time = 1;
	static RECT ss;

	switch (first_time) {
	  case 1:
	    /* Get the size of the screen */
	    if (get_fullscreen_rect(wnd, &ss))
		/* first_time = 0 */ ;
	    else {
		first_time = 2;
		break;
	    }
	  case 0:
	    /* Make sure the values are sane */
	    width = (ss.right - ss.left - wnd->extra_width) / 4;
	    height = (ss.bottom - ss.top - wnd->extra_height) / 6;

	    if (w > width || h > height)
		return;
	    if (w < 15)
		w = 15;
	    if (h < 1)
		h = 1;
	}
    }

    term_size(wnd->term, h, w, wnd->cfg.savelines);

    if (wnd->cfg.resize_action != RESIZE_FONT && !IsZoomed(wnd->hwnd)) {
	width = wnd->extra_width + wnd->font_width * w;
	height = wnd->extra_height + wnd->font_height * h;

	SetWindowPos(wnd->hwnd, NULL, 0, 0, width, height,
	    SWP_NOACTIVATE | SWP_NOCOPYBITS |
	    SWP_NOMOVE | SWP_NOZORDER);
    } else
	reset_window(wnd,0);

    InvalidateRect(wnd->hwnd, NULL, TRUE);
}

static void reset_window(SshWindow wnd, int reinit) {
    /*
     * This function decides how to resize or redraw when the 
     * user changes something. 
     *
     * This function doesn't like to change the terminal size but if the
     * font size is locked that may be it's only soluion.
     */
    int win_width, win_height;
    RECT cr, wr;

#ifdef RDB_DEBUG_PATCH
    debug((27, "reset_window(wnd,)"));
#endif

    /* Current window sizes ... */
    GetWindowRect(wnd->hwnd, &wr);
    GetClientRect(wnd->hwnd, &cr);

    win_width  = cr.right - cr.left;
    win_height = cr.bottom - cr.top;

    if (wnd->cfg.resize_action == RESIZE_DISABLED) reinit = 2;

    /* Are we being forced to reload the fonts ? */
    if (reinit>1) {
#ifdef RDB_DEBUG_PATCH
	debug((27, "reset_window(wnd,) -- Forced deinit"));
#endif
	deinit_fonts(wnd);
	init_fonts(wnd, 0,0);
    }

    /* Oh, looks like we're minimised */
    if (win_width == 0 || win_height == 0)
	return;

    /* Is the window out of position ? */
    if ( !reinit && 
	    (wnd->offset_width != (win_width-wnd->font_width*wnd->term->cols)/2 ||
	     wnd->offset_height != (win_height-wnd->font_height*wnd->term->rows)/2) ){
	wnd->offset_width = (win_width-wnd->font_width*wnd->term->cols)/2;
	wnd->offset_height = (win_height-wnd->font_height*wnd->term->rows)/2;
	InvalidateRect(wnd->hwnd, NULL, TRUE);
#ifdef RDB_DEBUG_PATCH
	debug((27, "reset_window(wnd,) -> Reposition terminal"));
#endif
    }

    if (IsZoomed(wnd->hwnd)) {
	/* We're fullscreen, this means we must not change the size of
	 * the window so it's the font size or the terminal itself.
	 */

	wnd->extra_width = wr.right - wr.left - cr.right + cr.left;
	wnd->extra_height = wr.bottom - wr.top - cr.bottom + cr.top;

	if (wnd->cfg.resize_action != RESIZE_TERM) {
	    if (  wnd->font_width != win_width/wnd->term->cols || 
		  wnd->font_height != win_height/wnd->term->rows) {
		deinit_fonts(wnd);
		init_fonts(wnd, win_width/wnd->term->cols, win_height/wnd->term->rows);
		wnd->offset_width = (win_width-wnd->font_width*wnd->term->cols)/2;
		wnd->offset_height = (win_height-wnd->font_height*wnd->term->rows)/2;
		InvalidateRect(wnd->hwnd, NULL, TRUE);
#ifdef RDB_DEBUG_PATCH
		debug((25, "reset_window(wnd,) -> Z font resize to (%d, %d)",
			wnd->font_width, wnd->font_height));
#endif
	    }
	} else {
	    if (  wnd->font_width * wnd->term->cols != win_width || 
		  wnd->font_height * wnd->term->rows != win_height) {
		/* Our only choice at this point is to change the 
		 * size of the terminal; Oh well.
		 */
		term_size(wnd->term, win_height/wnd->font_height, win_width/wnd->font_width,
			  wnd->cfg.savelines);
		wnd->offset_width = (win_width-wnd->font_width*wnd->term->cols)/2;
		wnd->offset_height = (win_height-wnd->font_height*wnd->term->rows)/2;
		InvalidateRect(wnd->hwnd, NULL, TRUE);
#ifdef RDB_DEBUG_PATCH
		debug((27, "reset_window(wnd,) -> Zoomed term_size"));
#endif
	    }
	}
	return;
    }

    /* Hmm, a force re-init means we should ignore the current window
     * so we resize to the default font size.
     */
    if (reinit>0) {
#ifdef RDB_DEBUG_PATCH
	debug((27, "reset_window(wnd,) -> Forced re-init"));
#endif

	wnd->offset_width = wnd->offset_height = wnd->cfg.window_border;
	wnd->extra_width = wr.right - wr.left - cr.right + cr.left + wnd->offset_width*2;
	wnd->extra_height = wr.bottom - wr.top - cr.bottom + cr.top +wnd->offset_height*2;

	if (win_width != wnd->font_width*wnd->term->cols + wnd->offset_width*2 ||
	    win_height != wnd->font_height*wnd->term->rows + wnd->offset_height*2) {

	    /* If this is too large windows will resize it to the maximum
	     * allowed window size, we will then be back in here and resize
	     * the font or terminal to fit.
	     */
	    SetWindowPos(wnd->hwnd, NULL, 0, 0, 
		         wnd->font_width*wnd->term->cols + wnd->extra_width, 
			 wnd->font_height*wnd->term->rows + wnd->extra_height,
			 SWP_NOMOVE | SWP_NOZORDER);
	}

	InvalidateRect(wnd->hwnd, NULL, TRUE);
	return;
    }

    /* Okay the user doesn't want us to change the font so we try the 
     * window. But that may be too big for the screen which forces us
     * to change the terminal.
     */
    if ((wnd->cfg.resize_action == RESIZE_TERM && reinit<=0) ||
        (wnd->cfg.resize_action == RESIZE_EITHER && reinit<0) ||
	    reinit>0) {
	wnd->offset_width = wnd->offset_height = wnd->cfg.window_border;
	wnd->extra_width = wr.right - wr.left - cr.right + cr.left + wnd->offset_width*2;
	wnd->extra_height = wr.bottom - wr.top - cr.bottom + cr.top +wnd->offset_height*2;

	if (win_width != wnd->font_width*wnd->term->cols + wnd->offset_width*2 ||
	    win_height != wnd->font_height*wnd->term->rows + wnd->offset_height*2) {

	    static RECT ss;
	    int width, height;
		
		get_fullscreen_rect(wnd, &ss);

	    width = (ss.right - ss.left - wnd->extra_width) / wnd->font_width;
	    height = (ss.bottom - ss.top - wnd->extra_height) / wnd->font_height;

	    /* Grrr too big */
	    if ( wnd->term->rows > height || wnd->term->cols > width ) {
		if (wnd->cfg.resize_action == RESIZE_EITHER) {
		    /* Make the font the biggest we can */
		    if (wnd->term->cols > width)
			wnd->font_width = (ss.right - ss.left - wnd->extra_width)
			    / wnd->term->cols;
		    if (wnd->term->rows > height)
			wnd->font_height = (ss.bottom - ss.top - wnd->extra_height)
			    / wnd->term->rows;

		    deinit_fonts(wnd);
		    init_fonts(wnd, wnd->font_width, wnd->font_height);

		    width = (ss.right - ss.left - wnd->extra_width) / wnd->font_width;
		    height = (ss.bottom - ss.top - wnd->extra_height) / wnd->font_height;
		} else {
		    if ( height > wnd->term->rows ) height = wnd->term->rows;
		    if ( width > wnd->term->cols )  width = wnd->term->cols;
		    term_size(wnd->term, height, width, wnd->cfg.savelines);
#ifdef RDB_DEBUG_PATCH
		    debug((27, "reset_window(wnd,) -> term resize to (%d,%d)",
			       height, width));
#endif
		}
	    }
	    
	    SetWindowPos(wnd->hwnd, NULL, 0, 0, 
		         wnd->font_width*wnd->term->cols + wnd->extra_width, 
			 wnd->font_height*wnd->term->rows + wnd->extra_height,
			 SWP_NOMOVE | SWP_NOZORDER);

	    InvalidateRect(wnd->hwnd, NULL, TRUE);
#ifdef RDB_DEBUG_PATCH
	    debug((27, "reset_window(wnd,) -> window resize to (%d,%d)",
			wnd->font_width*term->cols + wnd->extra_width,
			wnd->font_height*term->rows + wnd->extra_height));
#endif
	}
	return;
    }

    /* We're allowed to or must change the font but do we want to ?  */

    if (wnd->font_width != (win_width-wnd->cfg.window_border*2)/wnd->term->cols || 
	wnd->font_height != (win_height-wnd->cfg.window_border*2)/wnd->term->rows) {

	deinit_fonts(wnd);
	init_fonts(wnd, (win_width-wnd->cfg.window_border*2)/wnd->term->cols, 
		   (win_height-wnd->cfg.window_border*2)/wnd->term->rows);
	wnd->offset_width = (win_width-wnd->font_width*wnd->term->cols)/2;
	wnd->offset_height = (win_height-wnd->font_height*wnd->term->rows)/2;

	wnd->extra_width = wr.right - wr.left - cr.right + cr.left +wnd->offset_width*2;
	wnd->extra_height = wr.bottom - wr.top - cr.bottom + cr.top+wnd->offset_height*2;

	InvalidateRect(wnd->hwnd, NULL, TRUE);
#ifdef RDB_DEBUG_PATCH
	debug((25, "reset_window(wnd,) -> font resize to (%d,%d)", 
		   wnd->font_width, wnd->font_height));
#endif
    }
}

static void set_input_locale(SshWindow wnd,HKL kl)
{
    char lbuf[20];

    GetLocaleInfoA(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
		  lbuf, sizeof(lbuf));

    wnd->kbd_codepage = atoi(lbuf);
}

static void click(SshWindow wnd, Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
{
    int thistime = GetMessageTime();

    if (wnd->send_raw_mouse && !(wnd->cfg.mouse_override && shift)) {
	wnd->lastbtn = MBT_NOTHING;
	term_mouse(wnd->term, b, translate_button(wnd, b), MA_CLICK,
		   x, y, shift, ctrl, alt);
	return;
    }

    if (wnd->lastbtn == b && thistime - wnd->lasttime < wnd->dbltime) {
	wnd->lastact = (wnd->lastact == MA_CLICK ? MA_2CLK :
		   wnd->lastact == MA_2CLK ? MA_3CLK :
		   wnd->lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
    } else {
	wnd->lastbtn = b;
	wnd->lastact = MA_CLICK;
    }
    if (wnd->lastact != MA_NOTHING)
	term_mouse(wnd->term, b, translate_button(wnd, b), wnd->lastact,
		   x, y, shift, ctrl, alt);
    wnd->lasttime = thistime;
}

/*
 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
 * into a cooked one (SELECT, EXTEND, PASTE).
 */
static Mouse_Button translate_button(SshWindow wnd, Mouse_Button button)
{
    if (button == MBT_LEFT)
	return MBT_SELECT;
    if (button == MBT_MIDDLE)
	return wnd->cfg.mouse_is_xterm == 1 ? MBT_PASTE : MBT_EXTEND;
    if (button == MBT_RIGHT)
	return wnd->cfg.mouse_is_xterm == 1 ? MBT_EXTEND : MBT_PASTE;
    return MBT_NOTHING;			       /* shouldn't happen */
}

static void show_mouseptr(SshWindow wnd, int show)
{
    /* NB that the counter in ShowCursor() is also frobbed by
     * update_mouse_pointer() */
    static int cursor_visible = 1;
    if (!wnd->cfg.hide_mouseptr)	       /* override if this feature disabled */
	show = 1;
    if (cursor_visible && !show)
	ShowCursor(FALSE);
    else if (!cursor_visible && show)
	ShowCursor(TRUE);
    cursor_visible = show;
}

static int is_alt_pressed(void)
{
    BYTE keystate[256];
    int r = GetKeyboardState(keystate);
    if (!r)
	return FALSE;
    if (keystate[VK_MENU] & 0x80)
	return TRUE;
    if (keystate[VK_RMENU] & 0x80)
	return TRUE;
    return FALSE;
}

static int is_shift_pressed(void)
{
    BYTE keystate[256];
    int r = GetKeyboardState(keystate);
    if (!r)
	return FALSE;
    if (keystate[VK_SHIFT] & 0x80)
	return TRUE;
    return FALSE;
}

void reconf(SshWindow wnd, Config *cfg)
{
		Config prev_cfg;
		int init_lvl = 1;

		if (wnd->reconfiguring)
		    return;
		else
		    wnd->reconfiguring = TRUE;
		memcpy(&wnd->cfg,cfg, sizeof(Config));

		GetWindowTextA(wnd->hwnd, wnd->cfg.wintitle, sizeof(wnd->cfg.wintitle));
		prev_cfg = wnd->cfg;

		{
		    /* Gracefully unzoom if necessary */
		    if (IsZoomed(wnd->hwnd) &&
			(wnd->cfg.resize_action == RESIZE_DISABLED)) {
			ShowWindow(wnd->hwnd, SW_RESTORE);
		    }
		}

		free(wnd->logpal);
		/*
		 * Flush the line discipline's edit buffer in the
		 * case where local editing has just been disabled.
		 */
		if (wnd->ldisc)
			ldisc_send(wnd->ldisc, NULL, 0, 0, wnd->localid);
		if (wnd->pal)
		    DeleteObject(wnd->pal);
		wnd->logpal = NULL;
		wnd->pal = NULL;
		cfgtopalette(wnd);
		init_palette(wnd);

		/* Pass new config data to the terminal */
		term_reconfig(wnd->term, &wnd->cfg);

		/* Pass new config data to the back end */
		if (wnd->back)
			wnd->back->reconfig(wnd->backhandle, wnd->cfg.cfg);

		/* Screen size changed ? */
		if (wnd->cfg.cfg->height != prev_cfg.cfg->height ||
		    wnd->cfg.cfg->width != prev_cfg.cfg->width ||
		    wnd->cfg.savelines != prev_cfg.savelines ||
		    wnd->cfg.resize_action == RESIZE_FONT ||
		    (wnd->cfg.resize_action == RESIZE_EITHER && IsZoomed(wnd->hwnd)) ||
		    wnd->cfg.resize_action == RESIZE_DISABLED)
		    term_size(wnd->term, wnd->cfg.cfg->height, wnd->cfg.cfg->width, wnd->cfg.savelines);

		/* Enable or disable the scroll bar, etc */
		{
		    LONG nflg, flag = GetWindowLongPtr(wnd->hwnd, GWL_STYLE);
		    LONG nexflag, exflag =
			GetWindowLongPtr(wnd->hwnd, GWL_EXSTYLE);

		    nexflag = exflag;
		    if (wnd->cfg.alwaysontop != prev_cfg.alwaysontop) {
			if (wnd->cfg.alwaysontop) {
			    nexflag |= WS_EX_TOPMOST;
			    SetWindowPos(wnd->hwnd, HWND_TOPMOST, 0, 0, 0, 0,
					 SWP_NOMOVE | SWP_NOSIZE);
			} else {
			    nexflag &= ~(WS_EX_TOPMOST);
			    SetWindowPos(wnd->hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
					 SWP_NOMOVE | SWP_NOSIZE);
			}
		    }
		    if (wnd->cfg.sunken_edge)
			nexflag |= WS_EX_CLIENTEDGE;
		    else
			nexflag &= ~(WS_EX_CLIENTEDGE);

		    nflg = flag;
		    if (is_full_screen(wnd) ?
			wnd->cfg.scrollbar_in_fullscreen : wnd->cfg.scrollbar)
			nflg |= WS_VSCROLL;
		    else
			nflg &= ~WS_VSCROLL;

		    if (wnd->cfg.resize_action == RESIZE_DISABLED ||
                        is_full_screen(wnd))
			nflg &= ~WS_THICKFRAME;
		    else
			nflg |= WS_THICKFRAME;

		    if (wnd->cfg.resize_action == RESIZE_DISABLED)
			nflg &= ~WS_MAXIMIZEBOX;
		    else
			nflg |= WS_MAXIMIZEBOX;

		    if (nflg != flag || nexflag != exflag) {
			if (nflg != flag)
			    SetWindowLongPtr(wnd->hwnd, GWL_STYLE, nflg);
			if (nexflag != exflag)
			    SetWindowLongPtr(wnd->hwnd, GWL_EXSTYLE, nexflag);

			SetWindowPos(wnd->hwnd, NULL, 0, 0, 0, 0,
				     SWP_NOACTIVATE | SWP_NOCOPYBITS |
				     SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
				     SWP_FRAMECHANGED);

			init_lvl = 2;
		    }
		}

		/* Oops */
		if (wnd->cfg.resize_action == RESIZE_DISABLED && IsZoomed(wnd->hwnd)) {
		    force_normal(wnd->hwnd);
		    init_lvl = 2;
		}

		set_title(wnd, wnd->cfg.wintitle);
		if (IsIconic(wnd->hwnd)) {
		    SetWindowTextA(wnd->hwnd,
				  wnd->cfg.win_name_always ? wnd->window_name :
				  wnd->icon_name);
		}

		if (strcmp(wnd->cfg.font.name, prev_cfg.font.name) != 0 ||
		    strcmp(wnd->cfg.line_codepage, prev_cfg.line_codepage) != 0 ||
		    wnd->cfg.font.isbold != prev_cfg.font.isbold ||
		    wnd->cfg.font.height != prev_cfg.font.height ||
		    wnd->cfg.font.charset != prev_cfg.font.charset ||
		    wnd->cfg.font_quality != prev_cfg.font_quality ||
		    wnd->cfg.vtmode != prev_cfg.vtmode ||
		    wnd->cfg.bold_colour != prev_cfg.bold_colour ||
		    wnd->cfg.resize_action == RESIZE_DISABLED ||
		    wnd->cfg.resize_action == RESIZE_EITHER ||
		    (wnd->cfg.resize_action != prev_cfg.resize_action))
		    init_lvl = 2;

		InvalidateRect(wnd->hwnd, NULL, TRUE);
		reset_window(wnd,init_lvl);
}

int sshterm_wndproc(SshWindow wnd, UINT message,
				WPARAM wParam, LPARAM lParam)
{
    HDC hdc;
    static int ignore_clip = FALSE;
    static int need_backend_resize = FALSE;
    static int fullscr_on_max = FALSE;
    static UINT last_mousemove = 0;

    switch (message) {
      case WM_TIMER:
	if ((UINT_PTR)wParam == TIMING_TIMER_ID) {
	    long next;

	    KillTimer(wnd->hwnd, TIMING_TIMER_ID);
	    if (run_timers(get_next_time(), &next)) {
			timer_change_notify(next, wnd->hwnd);
	    } else {
	    }
	}
	return 1;

#define X_POS(l) ((int)(short)LOWORD(l))
#define Y_POS(l) ((int)(short)HIWORD(l))

#define TO_CHR_X(x) ((((x)<0 ? (x)-wnd->font_width+1 : (x))-wnd->offset_width) / wnd->font_width)
#define TO_CHR_Y(y) ((((y)<0 ? (y)-wnd->font_height+1: (y))-wnd->offset_height) / wnd->font_height)
      case WM_LBUTTONDOWN:
      case WM_MBUTTONDOWN:
      case WM_RBUTTONDOWN:
      case WM_LBUTTONUP:
      case WM_MBUTTONUP:
      case WM_RBUTTONUP:
	{
	    Mouse_Button button;
		int press;

	    switch (message) {
	      case WM_LBUTTONDOWN:
		button = MBT_LEFT;
		press = 1;
		break;
	      case WM_MBUTTONDOWN:
		button = MBT_MIDDLE;
		press = 1;
		break;
	      case WM_RBUTTONDOWN:
		button = MBT_RIGHT;
		press = 1;
		break;
	      case WM_LBUTTONUP:
		button = MBT_LEFT;
		press = 0;
		break;
	      case WM_MBUTTONUP:
		button = MBT_MIDDLE;
		press = 0;
		break;
	      case WM_RBUTTONUP:
		button = MBT_RIGHT;
		press = 0;
		break;
	      default:
		button = MBT_NOTHING;
		press = 0;    /* shouldn't happen */
	    }
	    show_mouseptr(wnd, 1);
	    /*
	     * Special case: in full-screen mode, if the left
	     * button is clicked in the very top left corner of the
	     * window, we put up the System menu instead of doing
	     * selection.
	     */
	    {
		char mouse_on_hotspot = 0;
		POINT pt;

		GetCursorPos(&pt);
#ifndef NO_MULTIMON
		{
		    HMONITOR mon;
		    MONITORINFO mi;

		    mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);

		    if (mon != NULL) {
			mi.cbSize = sizeof(MONITORINFO);
			GetMonitorInfo(mon, &mi);

			if (mi.rcMonitor.left == pt.x &&
			    mi.rcMonitor.top == pt.y) {
			    mouse_on_hotspot = 1;
			}
		    }
		}
#else
		if (pt.x == 0 && pt.y == 0) {
		    mouse_on_hotspot = 1;
		}
#endif
		if (is_full_screen(wnd) && press &&
		    button == MBT_LEFT && mouse_on_hotspot) {
		    SendMessage(wnd->hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
				MAKELPARAM(pt.x, pt.y));
		    return 1;
		}
	    }
	    if (press) {
		click(wnd, button,
		      TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
		      wParam & MK_SHIFT, wParam & MK_CONTROL,
		      is_alt_pressed());
		SetCapture(wnd->hwnd);
	    } else {
		term_mouse(wnd->term, button, translate_button(wnd, button), MA_RELEASE,
			   TO_CHR_X(X_POS(lParam)),
			   TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
			   wParam & MK_CONTROL, is_alt_pressed());
		ReleaseCapture();
	    }
	}
	return 1;
      case WM_MOUSEMOVE:
	{
	    /*
	     * Windows seems to like to occasionally send MOUSEMOVE
	     * events even if the mouse hasn't moved. Don't unhide
	     * the mouse pointer in this case.
	     */
	    static WPARAM wp = 0;
	    static LPARAM lp = 0;
	    if (wParam != wp || lParam != lp ||
		last_mousemove != WM_MOUSEMOVE) {
		show_mouseptr(wnd,1);
		wp = wParam; lp = lParam;
		last_mousemove = WM_MOUSEMOVE;
	    }
	}
	/*
	 * Add the mouse position and message time to the random
	 * number noise.
	 */

	if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
	    GetCapture() == wnd->hwnd) {
	    Mouse_Button b;
	    if (wParam & MK_LBUTTON)
		b = MBT_LEFT;
	    else if (wParam & MK_MBUTTON)
		b = MBT_MIDDLE;
	    else
		b = MBT_RIGHT;
	    term_mouse(wnd->term, b, translate_button(wnd, b), MA_DRAG,
		       TO_CHR_X(X_POS(lParam)),
		       TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
		       wParam & MK_CONTROL, is_alt_pressed());
	}
	return 1;
      case WM_NCMOUSEMOVE:
	{
	    static WPARAM wp = 0;
	    static LPARAM lp = 0;
	    if (wParam != wp || lParam != lp ||
		last_mousemove != WM_NCMOUSEMOVE) {
		show_mouseptr(wnd, 1);
		wp = wParam; lp = lParam;
		last_mousemove = WM_NCMOUSEMOVE;
	    }
	}
	break;
      case WM_IGNORE_CLIP:
	ignore_clip = wParam;	       /* don't panic on DESTROYCLIPBOARD */
	break;
      case WM_DESTROYCLIPBOARD:
	if (!ignore_clip)
	    term_deselect(wnd->term);
	ignore_clip = FALSE;
	return 1;
      case WM_PAINT:
	{
	    PAINTSTRUCT p;

	    HideCaret(wnd->hwnd);
	    hdc = BeginPaint(wnd->hwnd, &p);
	    if (wnd->pal) {
		SelectPalette(hdc, wnd->pal, TRUE);
		RealizePalette(hdc);
	    }

	    /*
	     * We have to be careful about term_paint(). It will
	     * set a bunch of character cells to INVALID and then
	     * call do_paint(), which will redraw those cells and
	     * _then mark them as done_. This may not be accurate:
	     * when painting in WM_PAINT context we are restricted
	     * to the rectangle which has just been exposed - so if
	     * that only covers _part_ of a character cell and the
	     * rest of it was already visible, that remainder will
	     * not be redrawn at all. Accordingly, we must not
	     * paint any character cell in a WM_PAINT context which
	     * already has a pending update due to terminal output.
	     * The simplest solution to this - and many, many
	     * thanks to Hung-Te Lin for working all this out - is
	     * not to do any actual painting at _all_ if there's a
	     * pending terminal update: just mark the relevant
	     * character cells as INVALID and wait for the
	     * scheduled full update to sort it out.
	     * 
	     * I have a suspicion this isn't the _right_ solution.
	     * An alternative approach would be to have terminal.c
	     * separately track what _should_ be on the terminal
	     * screen and what _is_ on the terminal screen, and
	     * have two completely different types of redraw (one
	     * for full updates, which syncs the former with the
	     * terminal itself, and one for WM_PAINT which syncs
	     * the latter with the former); yet another possibility
	     * would be to have the Windows front end do what the
	     * GTK one already does, and maintain a bitmap of the
	     * current terminal appearance so that WM_PAINT becomes
	     * completely trivial. However, this should do for now.
	     */
	    term_paint(wnd->term, hdc, 
		       (p.rcPaint.left-wnd->offset_width)/wnd->font_width,
		       (p.rcPaint.top-wnd->offset_height)/wnd->font_height,
		       (p.rcPaint.right-wnd->offset_width-1)/wnd->font_width,
		       (p.rcPaint.bottom-wnd->offset_height-1)/wnd->font_height,
		       !wnd->term->window_update_pending);

	    if (p.fErase ||
	        p.rcPaint.left  < wnd->offset_width  ||
		p.rcPaint.top   < wnd->offset_height ||
		p.rcPaint.right >= wnd->offset_width + wnd->font_width*wnd->term->cols ||
		p.rcPaint.bottom>= wnd->offset_height + wnd->font_height*wnd->term->rows)
	    {
		HBRUSH fillcolour, oldbrush;
		HPEN   edge, oldpen;
		fillcolour = CreateSolidBrush (
				    wnd->colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
		oldbrush = (HBRUSH)SelectObject(hdc, fillcolour);
		edge = CreatePen(PS_SOLID, 0, 
				    wnd->colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
		oldpen = (HPEN)SelectObject(hdc, edge);

		/*
		 * Jordan Russell reports that this apparently
		 * ineffectual IntersectClipRect() call masks a
		 * Windows NT/2K bug causing strange display
		 * problems when the PuTTY window is taller than
		 * the primary monitor. It seems harmless enough...
		 */
		IntersectClipRect(hdc,
			p.rcPaint.left, p.rcPaint.top,
			p.rcPaint.right, p.rcPaint.bottom);

		ExcludeClipRect(hdc, 
			wnd->offset_width, wnd->offset_height,
			wnd->offset_width+wnd->font_width*wnd->term->cols,
			wnd->offset_height+wnd->font_height*wnd->term->rows);

		Rectangle(hdc, p.rcPaint.left, p.rcPaint.top, 
			  p.rcPaint.right, p.rcPaint.bottom);

		/* SelectClipRgn(hdc, NULL); */

		SelectObject(hdc, oldbrush);
		DeleteObject(fillcolour);
		SelectObject(hdc, oldpen);
		DeleteObject(edge);
	    }
	    SelectObject(hdc, GetStockObject(SYSTEM_FONT));
	    SelectObject(hdc, GetStockObject(WHITE_PEN));
	    EndPaint(wnd->hwnd, &p);
	    ShowCaret(wnd->hwnd);
	}
	return 1;

      case WM_SETFOCUS:

	term_set_focus(wnd->term, TRUE);
	CreateCaret(wnd->hwnd, wnd->caretbm, wnd->font_width, wnd->font_height);
	ShowCaret(wnd->hwnd);
	flash_window(wnd, 0);	       /* stop */
	wnd->compose_state = 0;
	term_update(wnd->term);

	break;
      case WM_KILLFOCUS:

	show_mouseptr(wnd,1);
	term_set_focus(wnd->term, FALSE);
	DestroyCaret();
	wnd->caret_x = wnd->caret_y = -1;	       /* ensure caret is replaced next time */
	term_update(wnd->term);

	break;
      case WM_ENTERSIZEMOVE:
#ifdef RDB_DEBUG_PATCH
	debug((27, "WM_ENTERSIZEMOVE"));
#endif
	EnableSizeTip(1);
	wnd->resizing = TRUE;
	need_backend_resize = FALSE;
	break;
      case WM_EXITSIZEMOVE:
	EnableSizeTip(0);
	wnd->resizing = FALSE;
#ifdef RDB_DEBUG_PATCH
	debug((27, "WM_EXITSIZEMOVE"));
#endif
	if (need_backend_resize) {
	    term_size(wnd->term, wnd->cfg.cfg->height, wnd->cfg.cfg->width, wnd->cfg.savelines);
	    InvalidateRect(wnd->hwnd, NULL, TRUE);
	}
	break;
      case WM_SIZING:
	/*
	 * This does two jobs:
	 * 1) Keep the sizetip uptodate
	 * 2) Make sure the window size is _stepped_ in units of the font size.
	 */
	if (wnd->cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
	    int width, height, w, h, ew, eh;
	    LPRECT r = (LPRECT) lParam;

	    if ( !need_backend_resize && wnd->cfg.resize_action == RESIZE_EITHER &&
		    (wnd->cfg.cfg->height != wnd->term->rows || wnd->cfg.cfg->width != wnd->term->cols )) {
		/* 
		 * Great! It seems that both the terminal size and the
		 * font size have been changed and the user is now dragging.
		 * 
		 * It will now be difficult to get back to the configured
		 * font size!
		 *
		 * This would be easier but it seems to be too confusing.

		term_size(term, wnd->cfg.height, wnd->cfg.width, wnd->cfg.savelines);
		reset_window(wnd,2);
		 */
	        wnd->cfg.cfg->height=wnd->term->rows; wnd->cfg.cfg->width=wnd->term->cols;

		InvalidateRect(wnd->hwnd, NULL, TRUE);
		need_backend_resize = TRUE;
	    }

	    width = r->right - r->left - wnd->extra_width;
	    height = r->bottom - r->top - wnd->extra_height;
	    w = (width + wnd->font_width / 2) / wnd->font_width;
	    if (w < 1)
		w = 1;
	    h = (height + wnd->font_height / 2) / wnd->font_height;
	    if (h < 1)
		h = 1;
	    UpdateSizeTip(wnd->hwnd, w, h);
	    ew = width - w * wnd->font_width;
	    eh = height - h * wnd->font_height;
	    if (ew != 0) {
		if (wParam == WMSZ_LEFT ||
		    wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
		    r->left += ew;
		else
		    r->right -= ew;
	    }
	    if (eh != 0) {
		if (wParam == WMSZ_TOP ||
		    wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
		    r->top += eh;
		else
		    r->bottom -= eh;
	    }
	    if (ew || eh)
		return 1;
	    else
		return 1;
	} else {
	    int width, height, w, h, rv = 0;
	    int ex_width = wnd->extra_width + (wnd->cfg.window_border - wnd->offset_width) * 2;
	    int ex_height = wnd->extra_height + (wnd->cfg.window_border - wnd->offset_height) * 2;
	    LPRECT r = (LPRECT) lParam;

	    width = r->right - r->left - ex_width;
	    height = r->bottom - r->top - ex_height;

	    w = (width + wnd->term->cols/2)/wnd->term->cols;
	    h = (height + wnd->term->rows/2)/wnd->term->rows;
	    if ( r->right != r->left + w*wnd->term->cols + ex_width)
		rv = 1;

	    if (wParam == WMSZ_LEFT ||
		wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
		r->left = r->right - w*wnd->term->cols - ex_width;
	    else
		r->right = r->left + w*wnd->term->cols + ex_width;

	    if (r->bottom != r->top + h*wnd->term->rows + ex_height)
		rv = 1;

	    if (wParam == WMSZ_TOP ||
		wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
		r->top = r->bottom - h*wnd->term->rows - ex_height;
	    else
		r->bottom = r->top + h*wnd->term->rows + ex_height;

	    return rv;
	}
	/* break;  (never reached) */
      case WM_FULLSCR_ON_MAX:
	fullscr_on_max = TRUE;
	break;
      case WM_MOVE:
	sys_cursor_update(wnd);
	break;
      case WM_SIZE:
#ifdef RDB_DEBUG_PATCH
	debug((27, "WM_SIZE %s (%d,%d)",
		(wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
		(wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
		(wParam == SIZE_RESTORED && resizing) ? "to":
		(wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
		"...",
	    LOWORD(lParam), HIWORD(lParam)));
#endif
	if (wParam == SIZE_MINIMIZED)
	    SetWindowTextA(wnd->hwnd,
			  wnd->cfg.win_name_always ? wnd->window_name : wnd->icon_name);
	if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
	    SetWindowTextA(wnd->hwnd, wnd->window_name);
        if (wParam == SIZE_RESTORED)
            clear_full_screen(wnd);
        if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
            fullscr_on_max = FALSE;
            make_full_screen(wnd);
        }

	if (wnd->cfg.resize_action == RESIZE_DISABLED) {
	    /* A resize, well it better be a minimize. */
	    reset_window(wnd,-1);
	} else {

	    int width, height, w, h;

	    width = LOWORD(lParam);
	    height = HIWORD(lParam);

	    if (!wnd->resizing) {
		if (wParam == SIZE_MAXIMIZED && !wnd->was_zoomed) {
		    wnd->was_zoomed = 1;
		    wnd->prev_rows = wnd->term->rows;
		    wnd->prev_cols = wnd->term->cols;
		    if (wnd->cfg.resize_action == RESIZE_TERM) {
			w = width / wnd->font_width;
			if (w < 1) w = 1;
			h = height / wnd->font_height;
			if (h < 1) h = 1;

			term_size(wnd->term, h, w, wnd->cfg.savelines);
		    }
		    reset_window(wnd,0);
		} else if (wParam == SIZE_RESTORED && wnd->was_zoomed) {
		    wnd->was_zoomed = 0;
		    if (wnd->cfg.resize_action == RESIZE_TERM)
			term_size(wnd->term, wnd->prev_rows, wnd->prev_cols, wnd->cfg.savelines);
		    if (wnd->cfg.resize_action != RESIZE_FONT)
			reset_window(wnd,2);
		    else
			reset_window(wnd,0);
		}
		/* This is an unexpected resize, these will normally happen
		 * if the window is too large. Probably either the user
		 * selected a huge font or the screen size has changed.
		 *
		 * This is also called with minimize.
		 */
		else reset_window(wnd,-1);
	    }

	    /*
	     * Don't call back->size in mid-resize. (To prevent
	     * massive numbers of resize events getting sent
	     * down the connection during an NT opaque drag.)
	     */
	    if (wnd->resizing) {
		if (wnd->cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
		    need_backend_resize = TRUE;
		    w = (width-wnd->cfg.window_border*2) / wnd->font_width;
		    if (w < 1) w = 1;
		    h = (height-wnd->cfg.window_border*2) / wnd->font_height;
		    if (h < 1) h = 1;

		    wnd->cfg.cfg->height = h;
		    wnd->cfg.cfg->width = w;
	        } else 
		    reset_window(wnd,0);
	    }
	}
	sys_cursor_update(wnd);
	return 1;
      case WM_VSCROLL:
	switch (LOWORD(wParam)) {
	  case SB_BOTTOM:
	    term_scroll(wnd->term, -1, 0);
	    break;
	  case SB_TOP:
	    term_scroll(wnd->term, +1, 0);
	    break;
	  case SB_LINEDOWN:
	    term_scroll(wnd->term, 0, +1);
	    break;
	  case SB_LINEUP:
	    term_scroll(wnd->term, 0, -1);
	    break;
	  case SB_PAGEDOWN:
	    term_scroll(wnd->term, 0, +wnd->term->rows / 2);
	    break;
	  case SB_PAGEUP:
	    term_scroll(wnd->term, 0, -wnd->term->rows / 2);
	    break;
	  case SB_THUMBPOSITION:
	  case SB_THUMBTRACK:
	    term_scroll(wnd->term, 1, HIWORD(wParam));
	    break;
	}
	break;
      case WM_PALETTECHANGED:
	if ((HWND) wParam != wnd->hwnd && wnd->pal != NULL) {
	    HDC hdc = get_ctx(NULL);
	    if (hdc) {
		if (RealizePalette(hdc) > 0)
		    UpdateColors(hdc);
		free_ctx(wnd, hdc);
	    }
	}
	break;
      case WM_QUERYNEWPALETTE:
	if (wnd->pal != NULL) {
	    HDC hdc = get_ctx(NULL);
	    if (hdc) {
		if (RealizePalette(hdc) > 0)
		    UpdateColors(hdc);
		free_ctx(wnd, hdc);
		return TRUE;
	    }
	}
	return TRUE;
      case WM_KEYDOWN:
      case WM_SYSKEYDOWN:
      case WM_KEYUP:
      case WM_SYSKEYUP:
	/*
	 * Add the scan code and keypress timing to the random
	 * number noise.
	 */

	/*
	 * We don't do TranslateMessage since it disassociates the
	 * resulting CHAR message from the KEYDOWN that sparked it,
	 * which we occasionally don't want. Instead, we process
	 * KEYDOWN, and call the Win32 translator functions so that
	 * we get the translations under _our_ control.
	 */
	{
	    unsigned char buf[20];
	    int len;

	    if (wParam == VK_PROCESSKEY) { /* IME PROCESS key */
		if (message == WM_KEYDOWN) {
		    MSG m;
		    m.hwnd = wnd->hwnd;
		    m.message = WM_KEYDOWN;
		    m.wParam = wParam;
		    m.lParam = lParam & 0xdfff;
		    TranslateMessage(&m);
		} else break; /* pass to Windows for default processing */
	    } else {
		len = TranslateKey(wnd, message, wParam, lParam, buf);
		if (len == -1) {
		    break;
		}

		if (len != 0) {
		    /*
		     * Interrupt an ongoing paste. I'm not sure
		     * this is sensible, but for the moment it's
		     * preferable to having to faff about buffering
		     * things.
		     */
		    term_nopaste(wnd->term);

		    /*
		     * We need not bother about stdin backlogs
		     * here, because in GUI PuTTY we can't do
		     * anything about it anyway; there's no means
		     * of asking Windows to hold off on KEYDOWN
		     * messages. We _have_ to buffer everything
		     * we're sent.
		     */
		    term_seen_key_event(wnd->term);
		    if (wnd->ldisc)
				ldisc_send(wnd->ldisc, (char*)buf, len, 1, wnd->localid);
		    show_mouseptr(wnd,0);
		}
	    }
	}
	return 1;
      case WM_INPUTLANGCHANGE:
	/* wParam == Font number */
	/* lParam == Locale */
	set_input_locale(wnd, (HKL)lParam);
	sys_cursor_update(wnd);
	break;
      case WM_IME_STARTCOMPOSITION:
	{
	    HIMC hImc = ImmGetContext(wnd->hwnd);
	    ImmSetCompositionFont(hImc, &wnd->lfont);
	    ImmReleaseContext(wnd->hwnd, hImc);
	}
	break;
      case WM_IME_COMPOSITION:
	{
	    HIMC hIMC;
	    int n;
	    char *buff;

	    if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS || 
	        osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */

	    if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
		break; /* fall back to DefWindowProc */

	    hIMC = ImmGetContext(wnd->hwnd);
	    n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);

		if (n > 0) {
		int i;
		buff = memallocn(n, char);
		ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
		/*
		 * Jaeyoun Chung reports that Korean character
		 * input doesn't work correctly if we do a single
		 * luni_send() covering the whole of buff. So
		 * instead we luni_send the characters one by one.
		 */
		term_seen_key_event(wnd->term);
		for (i = 0; i < n; i += 2) {
		    if (wnd->ldisc)
			luni_send(wnd->ldisc,(wchar_t*)(buff+i), 1, 1);
		}
		free(buff);
	    }
	    ImmReleaseContext(wnd->hwnd, hIMC);
	    return 1;
	}

      case WM_IME_CHAR:
		  if (wParam & 0xFF00) {
	    unsigned char buf[2];

	    buf[1] = wParam;
	    buf[0] = wParam >> 8;
	    term_seen_key_event(wnd->term);
	    if (wnd->ldisc)
		lpage_send(wnd->ldisc, wnd->kbd_codepage, (char*)buf, 2, 1);
	} else {
	    char c = (unsigned char) wParam;
	    term_seen_key_event(wnd->term);
	    if (wnd->ldisc)
		lpage_send(wnd->ldisc, wnd->kbd_codepage, &c, 1, 1);
	}
	return 1;
      case WM_CHAR:
      case WM_SYSCHAR:
	/*
	 * Nevertheless, we are prepared to deal with WM_CHAR
	 * messages, should they crop up. So if someone wants to
	 * post the things to us as part of a macro manoeuvre,
	 * we're ready to cope.
	 */
	{
/*	    char c = (unsigned char)wParam;
	    term_seen_key_event(wnd->term);
	    if (wnd->ldisc)
		lpage_send(wnd->ldisc, CP_ACP, &c, 1, 1);*/
	}
	return 1;
      case WM_SYSCOLORCHANGE:
	if (wnd->cfg.system_colour) {
	    /* Refresh palette from system wnd->colours. */
	    /* XXX actually this zaps the entire palette. */
	    systopalette(wnd);
	    init_palette(wnd);
	    /* Force a repaint of the terminal window. */
	    term_invalidate(wnd->term);
	}
	break;
      default:
	if (message == wnd->wm_mousewheel || message == WM_MOUSEWHEEL) {
	    int shift_pressed=0, control_pressed=0;

	    if (message == WM_MOUSEWHEEL) {
		wnd->wheel_accumulator += (short)HIWORD(wParam);
		shift_pressed=LOWORD(wParam) & MK_SHIFT;
		control_pressed=LOWORD(wParam) & MK_CONTROL;
	    } else {
		BYTE keys[256];
		wnd->wheel_accumulator += (int)wParam;
		if (GetKeyboardState(keys)!=0) {
		    shift_pressed=keys[VK_SHIFT]&0x80;
		    control_pressed=keys[VK_CONTROL]&0x80;
		}
	    }

	    /* process events when the threshold is reached */
	    while (abs(wnd->wheel_accumulator) >= WHEEL_DELTA) {
		Mouse_Button b;

		/* reduce amount for next time */
		if (wnd->wheel_accumulator > 0) {
		    b = MBT_WHEEL_UP;
		    wnd->wheel_accumulator -= WHEEL_DELTA;
		} else if (wnd->wheel_accumulator < 0) {
		    b = MBT_WHEEL_DOWN;
		    wnd->wheel_accumulator += WHEEL_DELTA;
		} else
		    break;
		if (wnd->send_raw_mouse &&
			!(wnd->cfg.mouse_override && shift_pressed)) {
		    /* send a mouse-down followed by a mouse up */
		    term_mouse(wnd->term, b, translate_button(wnd, b),
			       MA_CLICK,
			       TO_CHR_X(X_POS(lParam)),
			       TO_CHR_Y(Y_POS(lParam)), shift_pressed,
			       control_pressed, is_alt_pressed());
		    term_mouse(wnd->term, b, translate_button(wnd,b),
			       MA_RELEASE, TO_CHR_X(X_POS(lParam)),
			       TO_CHR_Y(Y_POS(lParam)), shift_pressed,
			       control_pressed, is_alt_pressed());
		} else {
		    /* trigger a scroll */
		    term_scroll(wnd->term, 0,
				b == MBT_WHEEL_UP ?
				-wnd->term->rows / 2 : wnd->term->rows / 2);
		}
		}
	    return 1;
	}
    }

    return 0;
}

/*
 * Move the system caret. (We maintain one, even though it's
 * invisible, for the benefit of blind people: apparently some
 * helper software tracks the system caret, so we should arrange to
 * have one.)
 */
void sys_cursor(SshWindow wnd, int x, int y)
{
    int cx, cy;

    if (!wnd->term->has_focus) return;

    /*
     * Avoid gratuitously re-updating the cursor position and IMM
     * window if there's no actual change required.
     */
    cx = x * wnd->font_width + wnd->offset_width;
    cy = y * wnd->font_height + wnd->offset_height;
    if (cx == wnd->caret_x && cy == wnd->caret_y)
	return;
    wnd->caret_x = cx;
    wnd->caret_y = cy;

    sys_cursor_update(wnd);
}

static void sys_cursor_update(SshWindow wnd)
{
    COMPOSITIONFORM cf;
    HIMC hIMC;

    if (!wnd->term->has_focus) return;

    if (wnd->caret_x < 0 || wnd->caret_y < 0)
	return;

    SetCaretPos(wnd->caret_x, wnd->caret_y);

    /* IMM calls on Win98 and beyond only */
    if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
    
    if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
	    osVersion.dwMinorVersion == 0) return; /* 95 */

    /* we should have the IMM functions */
    hIMC = ImmGetContext(wnd->hwnd);
    cf.dwStyle = CFS_POINT;
    cf.ptCurrentPos.x = wnd->caret_x;
    cf.ptCurrentPos.y = wnd->caret_y;
    ImmSetCompositionWindow(hIMC, &cf);

    ImmReleaseContext(wnd->hwnd, hIMC);
}

/*
 * Draw a line of text in the window, at given character
 * coordinates, in given attributes.
 *
 * We are allowed to fiddle with the contents of `text'.
 */
void do_text_internal(SshWindow wnd, Context ctx, int x, int y, wchar_t *text, int len,
		      unsigned long attr, int lattr)
{
    COLORREF fg, bg, t;
    int nfg, nbg, nfont;
    HDC hdc = ctx;
    RECT line_box;
    int force_manual_underline = 0;
    int fnt_width, char_width;
    int text_adjust = 0;
    static int *IpDx = 0, IpDxLEN = 0;

    lattr &= LATTR_MODE;

    char_width = fnt_width = wnd->font_width * (1 + (lattr != LATTR_NORM));

    if (attr & ATTR_WIDE)
	char_width *= 2;

    if (len > IpDxLEN || IpDx[0] != char_width) {
	int i;
	if (len > IpDxLEN) {
	    memfree(IpDx);
	    IpDx = memallocn(len + 16, int);
	    IpDxLEN = (len + 16);
	}
	for (i = 0; i < IpDxLEN; i++)
	    IpDx[i] = char_width;
    }

    /* Only want the left half of double width lines */
    if (lattr != LATTR_NORM && x*2 >= wnd->term->cols)
	return;

    x *= fnt_width;
    y *= wnd->font_height;
    x += wnd->offset_width;
    y += wnd->offset_height;

    if ((attr & TATTR_ACTCURS) && (wnd->cfg.cursor_type == 0 || wnd->term->big_cursor)) {
	attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS);
	if (wnd->bold_mode == window_tag::BOLD_COLOURS)
	    attr &= ~ATTR_BOLD;

	/* cursor fg and bg */
	attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT);
    }

    nfont = 0;
	if (wnd->cfg.vtmode == VT_POORMAN && lattr != LATTR_NORM) {
	/* Assume a poorman font is borken in other ways too. */
	lattr = LATTR_WIDE;
    } else
	switch (lattr) {
	  case LATTR_NORM:
	    break;
	  case LATTR_WIDE:
	    nfont |= FONT_WIDE;
	    break;
	  default:
	    nfont |= FONT_WIDE + FONT_HIGH;
	    break;
	}
    if (attr & ATTR_NARROW)
	nfont |= FONT_NARROW;

    /* Special hack for the VT100 linedraw glyphs. */
    if (text[0] >= 0x23BA && text[0] <= 0x23BD) {
	switch ((unsigned char) (text[0])) {
	  case 0xBA:
	    text_adjust = -2 * wnd->font_height / 5;
	    break;
	  case 0xBB:
	    text_adjust = -1 * wnd->font_height / 5;
	    break;
	  case 0xBC:
	    text_adjust = wnd->font_height / 5;
	    break;
	  case 0xBD:
	    text_adjust = 2 * wnd->font_height / 5;
	    break;
	}
	if (lattr == LATTR_TOP || lattr == LATTR_BOT)
	    text_adjust *= 2;
	text[0] = wnd->ucsdata.unitab_xterm['q'];
	if (attr & ATTR_UNDER) {
	    attr &= ~ATTR_UNDER;
	    force_manual_underline = 1;
	}
    }

    /* Anything left as an original character set is unprintable. */
    if (DIRECT_CHAR(text[0])) {
	int i;
	for (i = 0; i < len; i++)
	    text[i] = 0xFFFD;
    }

    /* OEM CP */
    if ((text[0] & CSET_MASK) == CSET_OEMCP)
	nfont |= FONT_OEM;

    nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
    nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
	if (wnd->bold_mode == window_tag::BOLD_FONT && (attr & ATTR_BOLD))
	nfont |= FONT_BOLD;
	if (wnd->und_mode == window_tag::UND_FONT && (attr & ATTR_UNDER))
	nfont |= FONT_UNDERLINE;
    another_font(wnd, nfont);
    if (!wnd->fonts[nfont]) {
	if (nfont & FONT_UNDERLINE)
	    force_manual_underline = 1;
	/* Don't do the same for manual bold, it could be bad news. */

	nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
    }
    another_font(wnd, nfont);
    if (!wnd->fonts[nfont])
	nfont = FONT_NORMAL;
    if (attr & ATTR_REVERSE) {
	t = nfg;
	nfg = nbg;
	nbg = t;
    }
	if (wnd->bold_mode == window_tag::BOLD_COLOURS && (attr & ATTR_BOLD)) {
	if (nfg < 16) nfg |= 8;
	else if (nfg >= 256) nfg |= 1;
    }
	if (wnd->bold_mode == window_tag::BOLD_COLOURS && (attr & ATTR_BLINK)) {
	if (nbg < 16) nbg |= 8;
	else if (nbg >= 256) nbg |= 1;
    }
    fg = wnd->colours[nfg];
    bg = wnd->colours[nbg];
    SelectObject(hdc, wnd->fonts[nfont]);
    SetTextColor(hdc, fg);
    SetBkColor(hdc, bg);
    if (attr & TATTR_COMBINING)
	SetBkMode(hdc, TRANSPARENT);
    else
	SetBkMode(hdc, OPAQUE);
    line_box.left = x;
    line_box.top = y;
    line_box.right = x + char_width * len;
    line_box.bottom = y + wnd->font_height;

    /* Only want the left half of double width lines */
    if (line_box.right > wnd->font_width*wnd->term->cols+wnd->offset_width)
	line_box.right = wnd->font_width*wnd->term->cols+wnd->offset_width;

    /* We're using a private area for direct to font. (512 chars.) */
    if (wnd->ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {
	/* Ho Hum, dbcs fonts are a PITA! */
	/* To display on W9x I have to convert to UCS */
	static wchar_t *uni_buf = 0;
	static int uni_len = 0;
	int nlen, mptr;
	if (len > uni_len) {
	    memfree(uni_buf);
	    uni_len = len;
	    uni_buf = memallocn(uni_len, wchar_t);
	}

	for(nlen = mptr = 0; mptr<len; mptr++) {
	    uni_buf[nlen] = 0xFFFD;
	    if (IsDBCSLeadByteEx(wnd->ucsdata.font_codepage, (BYTE) text[mptr])) {
		char dbcstext[2];
		dbcstext[0] = text[mptr] & 0xFF;
		dbcstext[1] = text[mptr+1] & 0xFF;
		IpDx[nlen] += char_width;
	        MultiByteToWideChar(wnd->ucsdata.font_codepage, MB_USEGLYPHCHARS,
				    dbcstext, 2, uni_buf+nlen, 1);
		mptr++;
	    }
	    else
	    {
		char dbcstext[1];
		dbcstext[0] = text[mptr] & 0xFF;
	        MultiByteToWideChar(wnd->ucsdata.font_codepage, MB_USEGLYPHCHARS,
				    dbcstext, 1, uni_buf+nlen, 1);
	    }
	    nlen++;
	}
	if (nlen <= 0)
	    return;		       /* Eeek! */

	ExtTextOutW(hdc, x,
		    y - wnd->font_height * (lattr == LATTR_BOT) + text_adjust,
		    ETO_CLIPPED | ETO_OPAQUE, &line_box, uni_buf, nlen, IpDx);
	if (wnd->bold_mode == window_tag::BOLD_SHADOW && (attr & ATTR_BOLD)) {
	    SetBkMode(hdc, TRANSPARENT);
	    ExtTextOutW(hdc, x - 1,
			y - wnd->font_height * (lattr ==
					   LATTR_BOT) + text_adjust,
			ETO_CLIPPED, &line_box, uni_buf, nlen, IpDx);
	}

	IpDx[0] = -1;
    } else if (DIRECT_FONT(text[0])) {
	static char *directbuf = NULL;
	static int directlen = 0;
	int i;
	if (len > directlen) {
	    directlen = len;
	    directbuf = memrealloc(directbuf, directlen, char);
	}

	for (i = 0; i < len; i++)
	    directbuf[i] = text[i] & 0xFF;

	ExtTextOutA(hdc, x,
		   y - wnd->font_height * (lattr == LATTR_BOT) + text_adjust,
		   ETO_CLIPPED | ETO_OPAQUE, &line_box, directbuf, len, IpDx);
	if (wnd->bold_mode == window_tag::BOLD_SHADOW && (attr & ATTR_BOLD)) {
	    SetBkMode(hdc, TRANSPARENT);

	    /* GRR: This draws the character outside it's box and can leave
	     * 'droppings' even with the clip box! I suppose I could loop it
	     * one character at a time ... yuk. 
	     * 
	     * Or ... I could do a test print with "W", and use +1 or -1 for this
	     * shift depending on if the leftmost column is blank...
	     */
	    ExtTextOutA(hdc, x - 1,
		       y - wnd->font_height * (lattr ==
					  LATTR_BOT) + text_adjust,
		       ETO_CLIPPED, &line_box, directbuf, len, IpDx);
	}
    } else {
	/* And 'normal' unicode characters */
	static WCHAR *wbuf = NULL;
	static int wlen = 0;
	int i;

	if (wlen < len) {
	    memfree(wbuf);
	    wlen = len;
	    wbuf = memallocn(wlen, WCHAR);
	}

	for (i = 0; i < len; i++)
	    wbuf[i] = text[i];

	/* print Glyphs as they are, without Windows' Shaping*/
	general_textout(hdc, x, y - wnd->font_height * (lattr == LATTR_BOT) + text_adjust,
			&line_box, wbuf, len, IpDx, !(attr & TATTR_COMBINING));

	/* And the shadow bold hack. */
	if (wnd->bold_mode == window_tag::BOLD_SHADOW && (attr & ATTR_BOLD)) {
	    SetBkMode(hdc, TRANSPARENT);
	    ExtTextOutW(hdc, x - 1,
			y - wnd->font_height * (lattr ==
					   LATTR_BOT) + text_adjust,
			ETO_CLIPPED, &line_box, wbuf, len, IpDx);
	}
    }
    if (lattr != LATTR_TOP && (force_manual_underline ||
		(wnd->und_mode == window_tag::UND_LINE
				&& (attr & ATTR_UNDER)))) {
	HPEN oldpen;
	int dec = wnd->descent;
	if (lattr == LATTR_BOT)
	    dec = dec * 2 - wnd->font_height;

	oldpen = (HPEN)SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
	MoveToEx(hdc, x, y + dec, NULL);
	LineTo(hdc, x + len * char_width, y + dec);
	oldpen = (HPEN)SelectObject(hdc, oldpen);
	DeleteObject(oldpen);
    }
}

/*
 * Wrapper that handles combining characters.
 */
void do_text(SshWindow wnd, Context ctx, int x, int y, wchar_t *text, int len,
	     unsigned long attr, int lattr)
{
    if (attr & TATTR_COMBINING) {
	unsigned long a = 0;
	attr &= ~TATTR_COMBINING;
	while (len--) {
	    do_text_internal(wnd, ctx, x, y, text, 1, attr | a, lattr);
	    text++;
	    a = TATTR_COMBINING;
	}
    } else
	do_text_internal(wnd, ctx, x, y, text, len, attr, lattr);
}

void do_cursor(SshWindow wnd, Context ctx, int x, int y, wchar_t *text, int len,
	       unsigned long attr, int lattr)
{

    int fnt_width;
    int char_width;
    HDC hdc = ctx;
    int ctype = wnd->cfg.cursor_type;

    lattr &= LATTR_MODE;

    if ((attr & TATTR_ACTCURS) && (ctype == 0 || wnd->term->big_cursor)) {
	if (*text != UCSWIDE) {
	    do_text(wnd, ctx, x, y, text, len, attr, lattr);
	    return;
	}
	ctype = 2;
	attr |= TATTR_RIGHTCURS;
    }

    fnt_width = char_width = wnd->font_width * (1 + (lattr != LATTR_NORM));
    if (attr & ATTR_WIDE)
	char_width *= 2;
    x *= fnt_width;
    y *= wnd->font_height;
    x += wnd->offset_width;
    y += wnd->offset_height;

    if ((attr & TATTR_PASCURS) && (ctype == 0 || wnd->term->big_cursor)) {
	POINT pts[5];
	HPEN oldpen;
	pts[0].x = pts[1].x = pts[4].x = x;
	pts[2].x = pts[3].x = x + char_width - 1;
	pts[0].y = pts[3].y = pts[4].y = y;
	pts[1].y = pts[2].y = y + wnd->font_height - 1;
	oldpen = (HPEN)SelectObject(hdc, CreatePen(PS_SOLID, 0, wnd->colours[261]));
	Polyline(hdc, pts, 5);
	oldpen = (HPEN)SelectObject(hdc, oldpen);
	DeleteObject(oldpen);
    } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
	int startx, starty, dx, dy, length, i;
	if (ctype == 1) {
	    startx = x;
	    starty = y + wnd->descent;
	    dx = 1;
	    dy = 0;
	    length = char_width;
	} else {
	    int xadjust = 0;
	    if (attr & TATTR_RIGHTCURS)
		xadjust = char_width - 1;
	    startx = x + xadjust;
	    starty = y;
	    dx = 0;
	    dy = 1;
	    length = wnd->font_height;
	}
	if (attr & TATTR_ACTCURS) {
	    HPEN oldpen;
	    oldpen =
		(HPEN)SelectObject(hdc, CreatePen(PS_SOLID, 0, wnd->colours[261]));
	    MoveToEx(hdc, startx, starty, NULL);
	    LineTo(hdc, startx + dx * length, starty + dy * length);
	    oldpen = (HPEN)SelectObject(hdc, oldpen);
	    DeleteObject(oldpen);
	} else {
	    for (i = 0; i < length; i++) {
		if (i % 2 == 0) {
		    SetPixel(hdc, startx, starty, wnd->colours[261]);
		}
		startx += dx;
		starty += dy;
	    }
	}
    }
}

/* This function gets the actual width of a character in the normal font.
 */
int char_width(SshWindow wnd, Context ctx, int uc) {
    HDC hdc = ctx;
    int ibuf = 0;

    /* If the font max is the same as the font ave width then this
     * function is a no-op.
     */
    if (!wnd->font_dualwidth) return 1;

    switch (uc & CSET_MASK) {
      case CSET_ASCII:
	uc = wnd->ucsdata.unitab_line[uc & 0xFF];
	break;
      case CSET_LINEDRW:
	uc = wnd->ucsdata.unitab_xterm[uc & 0xFF];
	break;
      case CSET_SCOACS:
	uc = wnd->ucsdata.unitab_scoacs[uc & 0xFF];
	break;
    }
    if (DIRECT_FONT(uc)) {
	if (wnd->ucsdata.dbcs_screenfont) return 1;

	/* Speedup, I know of no font where ascii is the wrong width */
	if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')
	    return 1;

	if ( (uc & CSET_MASK) == CSET_ACP ) {
	    SelectObject(hdc, wnd->fonts[FONT_NORMAL]);
	} else if ( (uc & CSET_MASK) == CSET_OEMCP ) {
	    another_font(wnd, FONT_OEM);
	    if (!wnd->fonts[FONT_OEM]) return 0;

	    SelectObject(hdc, wnd->fonts[FONT_OEM]);
	} else
	    return 0;

	if ( GetCharWidth32(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1 &&
	     GetCharWidth(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1)
	    return 0;
    } else {
	/* Speedup, I know of no font where ascii is the wrong width */
	if (uc >= ' ' && uc <= '~') return 1;

	SelectObject(hdc, wnd->fonts[FONT_NORMAL]);
	if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
	    /* Okay that one worked */ ;
	else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
	    /* This should work on 9x too, but it's "less accurate" */ ;
	else
	    return 0;
    }

    ibuf += wnd->font_width / 2 -1;
    ibuf /= wnd->font_width;

    return ibuf;
}

/*
 * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
 * codes. Returns number of bytes used, zero to drop the message,
 * -1 to forward the message to Windows, or another negative number
 * to indicate a NUL-terminated "special" string.
 */
static int TranslateKey(SshWindow wnd, UINT message, WPARAM wParam, LPARAM lParam,
			unsigned char *output)
{
    BYTE keystate[256];
    int scan, left_alt = 0, key_down, shift_state;
    int r, i, code;
    unsigned char *p = output;
    static int alt_sum = 0;

    HKL kbd_layout = GetKeyboardLayout(0);

    /* keys is for ToAsciiEx. There's some ick here, see below. */
    static WORD keys[3];
    static int compose_char = 0;
    static WPARAM compose_key = 0;

    r = GetKeyboardState(keystate);
    if (!r)
	memset(keystate, 0, sizeof(keystate));
    else {
#if 0
#define SHOW_TOASCII_RESULT
	{			       /* Tell us all about key events */
	    static BYTE oldstate[256];
	    static int first = 1;
	    static int scan;
	    int ch;
	    if (first)
		memcpy(oldstate, keystate, sizeof(oldstate));
	    first = 0;

	    if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
		debug(("+"));
	    } else if ((HIWORD(lParam) & KF_UP)
		       && scan == (HIWORD(lParam) & 0xFF)) {
		debug((". U"));
	    } else {
		debug((".\n"));
		if (wParam >= VK_F1 && wParam <= VK_F20)
		    debug(("K_F%d", wParam + 1 - VK_F1));
		else
		    switch (wParam) {
		      case VK_SHIFT:
			debug(("SHIFT"));
			break;
		      case VK_CONTROL:
			debug(("CTRL"));
			break;
		      case VK_MENU:
			debug(("ALT"));
			break;
		      default:
			debug(("VK_%02x", wParam));
		    }
		if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
		    debug(("*"));
		debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));

		ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
		if (ch >= ' ' && ch <= '~')
		    debug((", '%c'", ch));
		else if (ch)
		    debug((", $%02x", ch));

		if (keys[0])
		    debug((", KB0=%02x", keys[0]));
		if (keys[1])
		    debug((", KB1=%02x", keys[1]));
		if (keys[2])
		    debug((", KB2=%02x", keys[2]));

		if ((keystate[VK_SHIFT] & 0x80) != 0)
		    debug((", S"));
		if ((keystate[VK_CONTROL] & 0x80) != 0)
		    debug((", C"));
		if ((HIWORD(lParam) & KF_EXTENDED))
		    debug((", E"));
		if ((HIWORD(lParam) & KF_UP))
		    debug((", U"));
	    }

	    if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
	    else if ((HIWORD(lParam) & KF_UP))
		oldstate[wParam & 0xFF] ^= 0x80;
	    else
		oldstate[wParam & 0xFF] ^= 0x81;

	    for (ch = 0; ch < 256; ch++)
		if (oldstate[ch] != keystate[ch])
		    debug((", M%02x=%02x", ch, keystate[ch]));

	    memcpy(oldstate, keystate, sizeof(oldstate));
	}
#endif

	if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
	    keystate[VK_RMENU] = keystate[VK_MENU];
	}


	/* Nastyness with NUMLock - Shift-NUMLock is left alone though */
	if ((wnd->cfg.funky_type == FUNKY_VT400 ||
	     (wnd->cfg.funky_type <= FUNKY_LINUX && wnd->term->app_keypad_keys &&
	      !wnd->cfg.no_applic_k))
	    && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {

	    wParam = VK_EXECUTE;

	    /* UnToggle NUMLock */
	    if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
		keystate[VK_NUMLOCK] ^= 1;
	}

	/* And write back the 'adjusted' state */
	SetKeyboardState(keystate);
    }

    /* Disable Auto repeat if required */
    if (wnd->term->repeat_off &&
	(HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
	return 0;

    if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
	left_alt = 1;

    key_down = ((HIWORD(lParam) & KF_UP) == 0);

    /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
    if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
	if (wnd->cfg.ctrlaltkeys)
	    keystate[VK_MENU] = 0;
	else {
	    keystate[VK_RMENU] = 0x80;
	    left_alt = 0;
	}
    }

    scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
    shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
	+ ((keystate[VK_CONTROL] & 0x80) != 0) * 2;

    /* Note if AltGr was pressed and if it was used as a compose key */
    if (!wnd->compose_state) {
	compose_key = 0x100;
	if (wnd->cfg.compose_key) {
	    if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
		compose_key = wParam;
	}
	if (wParam == VK_APPS)
	    compose_key = wParam;
    }

    if (wParam == compose_key) {
	if (wnd->compose_state == 0
	    && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) wnd->compose_state =
		1;
	else if (wnd->compose_state == 1 && (HIWORD(lParam) & KF_UP))
	    wnd->compose_state = 2;
	else
	    wnd->compose_state = 0;
    } else if (wnd->compose_state == 1 && wParam != VK_CONTROL)
	wnd->compose_state = 0;

    if (wnd->compose_state > 1 && left_alt)
	wnd->compose_state = 0;

    /* Sanitize the number pad if not using a PC NumPad */
    if (left_alt || (wnd->term->app_keypad_keys && !wnd->cfg.no_applic_k
		     && wnd->cfg.funky_type != FUNKY_XTERM)
	|| wnd->cfg.funky_type == FUNKY_VT400 || wnd->cfg.nethack_keypad || wnd->compose_state) {
	if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
	    int nParam = 0;
	    switch (wParam) {
	      case VK_INSERT:
		nParam = VK_NUMPAD0;
		break;
	      case VK_END:
		nParam = VK_NUMPAD1;
		break;
	      case VK_DOWN:
		nParam = VK_NUMPAD2;
		break;
	      case VK_NEXT:
		nParam = VK_NUMPAD3;
		break;
	      case VK_LEFT:
		nParam = VK_NUMPAD4;
		break;
	      case VK_CLEAR:
		nParam = VK_NUMPAD5;
		break;
	      case VK_RIGHT:
		nParam = VK_NUMPAD6;
		break;
	      case VK_HOME:
		nParam = VK_NUMPAD7;
		break;
	      case VK_UP:
		nParam = VK_NUMPAD8;
		break;
	      case VK_PRIOR:
		nParam = VK_NUMPAD9;
		break;
	      case VK_DELETE:
		nParam = VK_DECIMAL;
		break;
	    }
	    if (nParam) {
		if (keystate[VK_NUMLOCK] & 1)
		    shift_state |= 1;
		wParam = nParam;
	    }
	}
    }

    /* If a key is pressed and AltGr is not active */
    if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !wnd->compose_state) {
	/* Okay, prepare for most alts then ... */
	if (left_alt)
	    *p++ = '\033';

	/* Lets see if it's a pattern we know all about ... */
	if (wParam == VK_PRIOR && shift_state == 1) {
	    SendMessage(wnd->hwnd, WM_VSCROLL, SB_PAGEUP, 0);
	    return 0;
	}
	if (wParam == VK_PRIOR && shift_state == 2) {
	    SendMessage(wnd->hwnd, WM_VSCROLL, SB_LINEUP, 0);
	    return 0;
	}
	if (wParam == VK_NEXT && shift_state == 1) {
	    SendMessage(wnd->hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
	    return 0;
	}
	if (wParam == VK_NEXT && shift_state == 2) {
	    SendMessage(wnd->hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
	    return 0;
	}
	if (wParam == VK_INSERT && shift_state == 1) {
	    term_do_paste(wnd->term);
	    return 0;
	}
	if (left_alt && wParam == VK_F4 && wnd->cfg.alt_f4) {
	    return -1;
	}
	if (left_alt && wParam == VK_SPACE && wnd->cfg.alt_space) {
	    SendMessage(wnd->hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
	    return -1;
	}
	if (left_alt && wParam == VK_RETURN && wnd->cfg.fullscreenonaltenter &&
	    (wnd->cfg.resize_action != RESIZE_DISABLED)) {
 	    if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
 		flip_full_screen(wnd);
	    return -1;
	}
	/* Control-Numlock for app-keypad mode switch */
	if (wParam == VK_PAUSE && shift_state == 2) {
	    wnd->term->app_keypad_keys ^= 1;
	    return 0;
	}

	/* Nethack keypad */
	if (wnd->cfg.nethack_keypad && !left_alt) {
	    switch (wParam) {
	      case VK_NUMPAD1:
		*p++ = "bB\002\002"[shift_state & 3];
		return p - output;
	      case VK_NUMPAD2:
		*p++ = "jJ\012\012"[shift_state & 3];
		return p - output;
	      case VK_NUMPAD3:
		*p++ = "nN\016\016"[shift_state & 3];
		return p - output;
	      case VK_NUMPAD4:
		*p++ = "hH\010\010"[shift_state & 3];
		return p - output;
	      case VK_NUMPAD5:
		*p++ = shift_state ? '.' : '.';
		return p - output;
	      case VK_NUMPAD6:
		*p++ = "lL\014\014"[shift_state & 3];
		return p - output;
	      case VK_NUMPAD7:
		*p++ = "yY\031\031"[shift_state & 3];
		return p - output;
	      case VK_NUMPAD8:
		*p++ = "kK\013\013"[shift_state & 3];
		return p - output;
	      case VK_NUMPAD9:
		*p++ = "uU\025\025"[shift_state & 3];
		return p - output;
	    }
	}

	/* Application Keypad */
	if (!left_alt) {
	    int xkey = 0;

	    if (wnd->cfg.funky_type == FUNKY_VT400 ||
		(wnd->cfg.funky_type <= FUNKY_LINUX &&
		 wnd->term->app_keypad_keys && !wnd->cfg.no_applic_k)) switch (wParam) {
		  case VK_EXECUTE:
		    xkey = 'P';
		    break;
		  case VK_DIVIDE:
		    xkey = 'Q';
		    break;
		  case VK_MULTIPLY:
		    xkey = 'R';
		    break;
		  case VK_SUBTRACT:
		    xkey = 'S';
		    break;
		}
	    if (wnd->term->app_keypad_keys && !wnd->cfg.no_applic_k)
		switch (wParam) {
		  case VK_NUMPAD0:
		    xkey = 'p';
		    break;
		  case VK_NUMPAD1:
		    xkey = 'q';
		    break;
		  case VK_NUMPAD2:
		    xkey = 'r';
		    break;
		  case VK_NUMPAD3:
		    xkey = 's';
		    break;
		  case VK_NUMPAD4:
		    xkey = 't';
		    break;
		  case VK_NUMPAD5:
		    xkey = 'u';
		    break;
		  case VK_NUMPAD6:
		    xkey = 'v';
		    break;
		  case VK_NUMPAD7:
		    xkey = 'w';
		    break;
		  case VK_NUMPAD8:
		    xkey = 'x';
		    break;
		  case VK_NUMPAD9:
		    xkey = 'y';
		    break;

		  case VK_DECIMAL:
		    xkey = 'n';
		    break;
		  case VK_ADD:
		    if (wnd->cfg.funky_type == FUNKY_XTERM) {
			if (shift_state)
			    xkey = 'l';
			else
			    xkey = 'k';
		    } else if (shift_state)
			xkey = 'm';
		    else
			xkey = 'l';
		    break;

		  case VK_DIVIDE:
		    if (wnd->cfg.funky_type == FUNKY_XTERM)
			xkey = 'o';
		    break;
		  case VK_MULTIPLY:
		    if (wnd->cfg.funky_type == FUNKY_XTERM)
			xkey = 'j';
		    break;
		  case VK_SUBTRACT:
		    if (wnd->cfg.funky_type == FUNKY_XTERM)
			xkey = 'm';
		    break;

		  case VK_RETURN:
		    if (HIWORD(lParam) & KF_EXTENDED)
			xkey = 'M';
		    break;
		}
	    if (xkey) {
		if (wnd->term->vt52_mode) {
		    if (xkey >= 'P' && xkey <= 'S')
			p += sprintf((char *) p, "\x1B%c", xkey);
		    else
			p += sprintf((char *) p, "\x1B?%c", xkey);
		} else
		    p += sprintf((char *) p, "\x1BO%c", xkey);
		return p - output;
	    }
	}

	if (wParam == VK_BACK && shift_state == 0) {	/* Backspace */
	    *p++ = (wnd->cfg.bksp_is_delete ? 0x7F : 0x08);
	    *p++ = 0;
	    return -2;
	}
	if (wParam == VK_BACK && shift_state == 1) {	/* Shift Backspace */
	    /* We do the opposite of what is configured */
	    *p++ = (wnd->cfg.bksp_is_delete ? 0x08 : 0x7F);
	    *p++ = 0;
	    return -2;
	}
	if (wParam == VK_TAB && shift_state == 1) {	/* Shift tab */
	    *p++ = 0x1B;
	    *p++ = '[';
	    *p++ = 'Z';
	    return p - output;
	}
	if (wParam == VK_SPACE && shift_state == 2) {	/* Ctrl-Space */
	    *p++ = 0;
	    return p - output;
	}
	if (wParam == VK_SPACE && shift_state == 3) {	/* Ctrl-Shift-Space */
	    *p++ = 160;
	    return p - output;
	}
	if (wParam == VK_CANCEL && shift_state == 2) {	/* Ctrl-Break */
	    if (wnd->back)
			wnd->back->special(wnd->backhandle, TS_BRK, wnd->localid);
	    return 0;
	}
	if (wParam == VK_PAUSE) {      /* Break/Pause */
	    *p++ = 26;
	    *p++ = 0;
	    return -2;
	}
	/* Control-2 to Control-8 are special */
	if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
	    *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
	    return p - output;
	}
	if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
	    *p++ = 0x1F;
	    return p - output;
	}
	if (shift_state == 2 && wParam == 0xDF) {
	    *p++ = 0x1C;
	    return p - output;
	}
	if (shift_state == 3 && wParam == 0xDE) {
	    *p++ = 0x1E;	       /* Ctrl-~ == Ctrl-^ in xterm at least */
	    return p - output;
	}
	if (shift_state == 0 && wParam == VK_RETURN && wnd->term->cr_lf_return) {
	    *p++ = '\r';
	    *p++ = '\n';
	    return p - output;
	}

	/*
	 * Next, all the keys that do tilde codes. (ESC '[' nn '~',
	 * for integer decimal nn.)
	 *
	 * We also deal with the weird ones here. Linux VCs replace F1
	 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
	 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
	 * respectively.
	 */
	code = 0;
	switch (wParam) {
	  case VK_F1:
	    code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
	    break;
	  case VK_F2:
	    code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
	    break;
	  case VK_F3:
	    code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
	    break;
	  case VK_F4:
	    code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
	    break;
	  case VK_F5:
	    code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
	    break;
	  case VK_F6:
	    code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
	    break;
	  case VK_F7:
	    code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
	    break;
	  case VK_F8:
	    code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
	    break;
	  case VK_F9:
	    code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
	    break;
	  case VK_F10:
	    code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
	    break;
	  case VK_F11:
	    code = 23;
	    break;
	  case VK_F12:
	    code = 24;
	    break;
	  case VK_F13:
	    code = 25;
	    break;
	  case VK_F14:
	    code = 26;
	    break;
	  case VK_F15:
	    code = 28;
	    break;
	  case VK_F16:
	    code = 29;
	    break;
	  case VK_F17:
	    code = 31;
	    break;
	  case VK_F18:
	    code = 32;
	    break;
	  case VK_F19:
	    code = 33;
	    break;
	  case VK_F20:
	    code = 34;
	    break;
	}
	if ((shift_state&2) == 0) switch (wParam) {
	  case VK_HOME:
	    code = 1;
	    break;
	  case VK_INSERT:
	    code = 2;
	    break;
	  case VK_DELETE:
	    code = 3;
	    break;
	  case VK_END:
	    code = 4;
	    break;
	  case VK_PRIOR:
	    code = 5;
	    break;
	  case VK_NEXT:
	    code = 6;
	    break;
	}
	/* Reorder edit keys to physical order */
	if (wnd->cfg.funky_type == FUNKY_VT400 && code <= 6)
	    code = "\0\2\1\4\5\3\6"[code];

	if (wnd->term->vt52_mode && code > 0 && code <= 6) {
	    p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
	    return p - output;
	}

	if (wnd->cfg.funky_type == FUNKY_SCO &&     /* SCO function keys */
	    code >= 11 && code <= 34) {
	    char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
	    int index = 0;
	    switch (wParam) {
	      case VK_F1: index = 0; break;
	      case VK_F2: index = 1; break;
	      case VK_F3: index = 2; break;
	      case VK_F4: index = 3; break;
	      case VK_F5: index = 4; break;
	      case VK_F6: index = 5; break;
	      case VK_F7: index = 6; break;
	      case VK_F8: index = 7; break;
	      case VK_F9: index = 8; break;
	      case VK_F10: index = 9; break;
	      case VK_F11: index = 10; break;
	      case VK_F12: index = 11; break;
	    }
	    if (keystate[VK_SHIFT] & 0x80) index += 12;
	    if (keystate[VK_CONTROL] & 0x80) index += 24;
	    p += sprintf((char *) p, "\x1B[%c", codes[index]);
	    return p - output;
	}
	if (wnd->cfg.funky_type == FUNKY_SCO &&     /* SCO small keypad */
	    code >= 1 && code <= 6) {
	    char codes[] = "HL.FIG";
	    if (code == 3) {
		*p++ = '\x7F';
	    } else {
		p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
	    }
	    return p - output;
	}
	if ((wnd->term->vt52_mode || wnd->cfg.funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {
	    int offt = 0;
	    if (code > 15)
		offt++;
	    if (code > 21)
		offt++;
	    if (wnd->term->vt52_mode)
		p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
	    else
		p +=
		    sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
	    return p - output;
	}
	if (wnd->cfg.funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
	    p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
	    return p - output;
	}
	if (wnd->cfg.funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
	    if (wnd->term->vt52_mode)
		p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
	    else
		p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
	    return p - output;
	}
	if (wnd->cfg.rxvt_homeend && (code == 1 || code == 4)) {
	    p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
	    return p - output;
	}
	if (code) {
	    p += sprintf((char *) p, "\x1B[%d~", code);
	    return p - output;
	}

	/*
	 * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
	 * some reason seems to send VK_CLEAR to Windows...).
	 */
	{
	    char xkey = 0;
	    switch (wParam) {
	      case VK_UP:
		xkey = 'A';
		break;
	      case VK_DOWN:
		xkey = 'B';
		break;
	      case VK_RIGHT:
		xkey = 'C';
		break;
	      case VK_LEFT:
		xkey = 'D';
		break;
	      case VK_CLEAR:
		xkey = 'G';
		break;
	    }
	    if (xkey) {
		if (wnd->term->vt52_mode)
		    p += sprintf((char *) p, "\x1B%c", xkey);
		else {
		    int app_flg = (wnd->term->app_cursor_keys && !wnd->cfg.no_applic_c);
#if 0
		    /*
		     * RDB: VT100 & VT102 manuals both state the
		     * app cursor keys only work if the app keypad
		     * is on.
		     * 
		     * SGT: That may well be true, but xterm
		     * disagrees and so does at least one
		     * application, so I've #if'ed this out and the
		     * behaviour is back to PuTTY's original: app
		     * cursor and app keypad are independently
		     * switchable modes. If anyone complains about
		     * _this_ I'll have to put in a configurable
		     * option.
		     */
		    if (!term->app_keypad_keys)
			app_flg = 0;
#endif
		    /* Useful mapping of Ctrl-arrows */
		    if (shift_state == 2)
			app_flg = !app_flg;

		    if (app_flg)
			p += sprintf((char *) p, "\x1BO%c", xkey);
		    else
			p += sprintf((char *) p, "\x1B[%c", xkey);
		}
		return p - output;
	    }
	}

	/*
	 * Finally, deal with Return ourselves. (Win95 seems to
	 * foul it up when Alt is pressed, for some reason.)
	 */
	if (wParam == VK_RETURN) {     /* Return */
	    *p++ = 0x0D;
	    *p++ = 0;
	    return -2;
	}

	if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
	    alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
	else
	    alt_sum = 0;
    }

    /* Okay we've done everything interesting; let windows deal with 
     * the boring stuff */
    {
	BOOL capsOn=0;

	/* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
	if(wnd->cfg.xlat_capslockcyr && keystate[VK_CAPITAL] != 0) {
	    capsOn= !left_alt;
	    keystate[VK_CAPITAL] = 0;
	}

	/* XXX how do we know what the max size of the keys array should
	 * be is? There's indication on MS' website of an Inquire/InquireEx
	 * functioning returning a KBINFO structure which tells us. */
	if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT) {
	    /* XXX 'keys' parameter is declared in MSDN documentation as
	     * 'LPWORD lpChar'.
	     * The experience of a French user indicates that on
	     * Win98, WORD[] should be passed in, but on Win2K, it should
	     * be BYTE[]. German WinXP and my Win2K with "US International"
	     * driver corroborate this.
	     * Experimentally I've conditionalised the behaviour on the
	     * Win9x/NT split, but I suspect it's worse than that.
	     * See wishlist item `win-dead-keys' for more horrible detail
	     * and speculations. */
	    BYTE keybs[3];
	    int i;
	    r = ToAsciiEx(wParam, scan, keystate, (LPWORD)keybs, 0, kbd_layout);
	    for (i=0; i<3; i++) keys[i] = keybs[i];
	} else {
	    r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
	}
#ifdef SHOW_TOASCII_RESULT
	if (r == 1 && !key_down) {
	    if (alt_sum) {
		if (in_utf(term) || wnd->ucsdata.dbcs_screenfont)
		    debug((", (U+%04x)", alt_sum));
		else
		    debug((", LCH(%d)", alt_sum));
	    } else {
		debug((", ACH(%d)", keys[0]));
	    }
	} else if (r > 0) {
	    int r1;
	    debug((", ASC("));
	    for (r1 = 0; r1 < r; r1++) {
		debug(("%s%d", r1 ? "," : "", keys[r1]));
	    }
	    debug((")"));
	}
#endif
	if (r > 0) {
	    WCHAR keybuf;

	    /*
	     * Interrupt an ongoing paste. I'm not sure this is
	     * sensible, but for the moment it's preferable to
	     * having to faff about buffering things.
	     */
	    term_nopaste(wnd->term);

	    p = output;
	    for (i = 0; i < r; i++) {
		unsigned char ch = (unsigned char) keys[i];

		if (wnd->compose_state == 2 && (ch & 0x80) == 0 && ch > ' ') {
		    compose_char = ch;
		    wnd->compose_state++;
		    continue;
		}
		if (wnd->compose_state == 3 && (ch & 0x80) == 0 && ch > ' ') {
		    int nc;
		    wnd->compose_state = 0;

		    if ((nc = check_compose(compose_char, ch)) == -1) {
			MessageBeep(MB_ICONHAND);
			return 0;
		    }
		    keybuf = nc;
		    term_seen_key_event(wnd->term);
		    if (wnd->ldisc)
			luni_send(wnd->ldisc, &keybuf, 1, 1);
		    continue;
		}

		wnd->compose_state = 0;

		if (!key_down) {
		    if (alt_sum) {
			if (in_utf(wnd->term) || wnd->ucsdata.dbcs_screenfont) {
			    keybuf = alt_sum;
			    term_seen_key_event(wnd->term);
			    if (wnd->ldisc)
				luni_send(wnd->ldisc, &keybuf, 1, 1);
			} else {
			    ch = (char) alt_sum;
			    /*
			     * We need not bother about stdin
			     * backlogs here, because in GUI PuTTY
			     * we can't do anything about it
			     * anyway; there's no means of asking
			     * Windows to hold off on KEYDOWN
			     * messages. We _have_ to buffer
			     * everything we're sent.
			     */
			    term_seen_key_event(wnd->term);
			    if (wnd->ldisc)
				ldisc_send(wnd->ldisc, (char*)&ch, 1, 1, wnd->localid);
			}
			alt_sum = 0;
		    } else {
			term_seen_key_event(wnd->term);
			if (wnd->ldisc)
			    lpage_send(wnd->ldisc, wnd->kbd_codepage, (char*)&ch, 1, 1);
		    }
		} else {
		    if(capsOn && ch < 0x80) {
			WCHAR cbuf[2];
			cbuf[0] = 27;
			cbuf[1] = xlat_uskbd2cyrllic(ch);
			term_seen_key_event(wnd->term);
			if (wnd->ldisc)
			    luni_send(wnd->ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
		    } else {
			char cbuf[2];
			cbuf[0] = '\033';
			cbuf[1] = ch;
			term_seen_key_event(wnd->term);
			if (wnd->ldisc)
			    lpage_send(wnd->ldisc, wnd->kbd_codepage,
				       cbuf+!left_alt, 1+!!left_alt, 1);
		    }
		}
		show_mouseptr(wnd,0);
	    }

	    /* This is so the ALT-Numpad and dead keys work correctly. */
	    keys[0] = 0;

	    return p - output;
	}
	/* If we're definitly not building up an ALT-54321 then clear it */
	if (!left_alt)
	    keys[0] = 0;
	/* If we will be using alt_sum fix the 256s */
	else if (keys[0] && (in_utf(wnd->term) || wnd->ucsdata.dbcs_screenfont))
	    keys[0] = 10;
    }

    /*
     * ALT alone may or may not want to bring up the System menu.
     * If it's not meant to, we return 0 on presses or releases of
     * ALT, to show that we've swallowed the keystroke. Otherwise
     * we return -1, which means Windows will give the keystroke
     * its default handling (i.e. bring up the System menu).
     */
    if (wParam == VK_MENU && !wnd->cfg.alt_only)
	return 0;

    return -1;
}

void request_paste(SshWindow wnd)
{
    /*
     * In Windows, pasting is synchronous: we can read the
     * clipboard with no difficulty, so request_paste() can just go
     * ahead and paste.
     */
    term_do_paste(wnd->term);
}

void set_title(SshWindow wnd, char *title)
{
    memfree(wnd->window_name);
    wnd->window_name = memallocn(1 + strlen(title), char);
    strcpy(wnd->window_name, title);
    if (wnd->cfg.win_name_always || !IsIconic(wnd->hwnd))
	SetWindowTextA(wnd->hwnd, title);
}

void set_icon(SshWindow wnd, char *title)
{
    memfree(wnd->icon_name);
    wnd->icon_name = memallocn(1 + strlen(title), char);
    strcpy(wnd->icon_name, title);
    if (!wnd->cfg.win_name_always && IsIconic(wnd->hwnd))
	SetWindowTextA(wnd->hwnd, title);
}

void set_sbar(SshWindow wnd, int total, int start, int page)
{
    SCROLLINFO si;

    if (is_full_screen(wnd) ? !wnd->cfg.scrollbar_in_fullscreen : !wnd->cfg.scrollbar)
	return;

    si.cbSize = sizeof(si);
    si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
    si.nMin = 0;
    si.nMax = total - 1;
    si.nPage = page;
    si.nPos = start;
    if (wnd->hwnd)
	SetScrollInfo(wnd->hwnd, SB_VERT, &si, TRUE);
}

Context get_ctx(SshWindow wnd)
{
    HDC hdc;
    if (wnd->hwnd) {
	hdc = GetDC(wnd->hwnd);
	if (hdc && wnd->pal)
	    SelectPalette(hdc, wnd->pal, FALSE);
	return hdc;
    } else
	return NULL;
}

void free_ctx(SshWindow wnd, Context ctx)
{
    SelectPalette(ctx, (HPALETTE)GetStockObject(DEFAULT_PALETTE), FALSE);
    ReleaseDC(wnd->hwnd, ctx);
}

static void real_palette_set(SshWindow wnd, int n, int r, int g, int b)
{
    if (wnd->pal) {
	wnd->logpal->palPalEntry[n].peRed = r;
	wnd->logpal->palPalEntry[n].peGreen = g;
	wnd->logpal->palPalEntry[n].peBlue = b;
	wnd->logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
	wnd->colours[n] = PALETTERGB(r, g, b);
	SetPaletteEntries(wnd->pal, 0, NALLCOLOURS, wnd->logpal->palPalEntry);
    } else
	wnd->colours[n] = RGB(r, g, b);
}

void palette_set(SshWindow wnd, int n, int r, int g, int b)
{
    if (n >= 16)
	n += 256 - 16;
    if (n > NALLCOLOURS)
	return;
    real_palette_set(wnd, n, r, g, b);
    if (wnd->pal) {
	HDC hdc = get_ctx(wnd);
	UnrealizeObject(wnd->pal);
	RealizePalette(hdc);
	free_ctx(wnd, hdc);
    } else {
	if (n == (ATTR_DEFBG>>ATTR_BGSHIFT))
	    /* If Default Background changes, we need to ensure any
	     * space between the text area and the window border is
	     * redrawn. */
	    InvalidateRect(wnd->hwnd, NULL, TRUE);
    }
}

void palette_reset(SshWindow wnd)
{
    int i;

    /* And this */
    for (i = 0; i < NALLCOLOURS; i++) {
	if (wnd->pal) {
	    wnd->logpal->palPalEntry[i].peRed = wnd->defpal[i].rgbtRed;
	    wnd->logpal->palPalEntry[i].peGreen = wnd->defpal[i].rgbtGreen;
	    wnd->logpal->palPalEntry[i].peBlue = wnd->defpal[i].rgbtBlue;
	    wnd->logpal->palPalEntry[i].peFlags = 0;
	    wnd->colours[i] = PALETTERGB(wnd->defpal[i].rgbtRed,
				    wnd->defpal[i].rgbtGreen,
				    wnd->defpal[i].rgbtBlue);
	} else
	    wnd->colours[i] = RGB(wnd->defpal[i].rgbtRed,
			     wnd->defpal[i].rgbtGreen, wnd->defpal[i].rgbtBlue);
    }

    if (wnd->pal) {
	HDC hdc;
	SetPaletteEntries(wnd->pal, 0, NALLCOLOURS, wnd->logpal->palPalEntry);
	hdc = get_ctx(wnd);
	RealizePalette(hdc);
	free_ctx(wnd, hdc);
    } else {
	/* Default Background may have changed. Ensure any space between
	 * text area and window border is redrawn. */
	InvalidateRect(wnd->hwnd, NULL, TRUE);
    }
}

void write_aclip(SshWindow wnd, char *data, int len, int must_deselect)
{
    HGLOBAL clipdata;
    void *lock;

    clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
    if (!clipdata)
	return;
    lock = GlobalLock(clipdata);
    if (!lock)
	return;
    memcpy(lock, data, len);
    ((unsigned char *) lock)[len] = 0;
    GlobalUnlock(clipdata);

    if (!must_deselect)
	SendMessage(wnd->hwnd, WM_IGNORE_CLIP, TRUE, 0);

    if (OpenClipboard(wnd->hwnd)) {
	EmptyClipboard();
	SetClipboardData(CF_TEXT, clipdata);
	CloseClipboard();
    } else
	GlobalFree(clipdata);

    if (!must_deselect)
	SendMessage(wnd->hwnd, WM_IGNORE_CLIP, FALSE, 0);
}

/*
 * Note: unlike write_aclip() this will not append a nul.
 */
void write_clip(SshWindow wnd, wchar_t * data, int *attr, int len, int must_deselect)
{
    HGLOBAL clipdata, clipdata2, clipdata3;
    int len2;
    void *lock, *lock2, *lock3;

    len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);

    clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
			   len * sizeof(wchar_t));
    clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);

    if (!clipdata || !clipdata2) {
	if (clipdata)
	    GlobalFree(clipdata);
	if (clipdata2)
	    GlobalFree(clipdata2);
	return;
    }
    if (!(lock = GlobalLock(clipdata)))
	return;
    if (!(lock2 = GlobalLock(clipdata2)))
	return;

    memcpy(lock, data, len * sizeof(wchar_t));
    WideCharToMultiByte(CP_ACP, 0, data, len, (LPSTR)lock2, len2, NULL, NULL);

    if (wnd->cfg.rtf_paste) {
	wchar_t unitab[256];
	char *rtf = NULL;
	unsigned char *tdata = (unsigned char *)lock2;
	wchar_t *udata = (wchar_t *)lock;
	int rtflen = 0, uindex = 0, tindex = 0;
	int rtfsize = 0;
	int multilen, blen, alen, totallen, i;
	char before[16], after[4];
	int fgcolour,  lastfgcolour  = 0;
	int bgcolour,  lastbgcolour  = 0;
	int attrBold,  lastAttrBold  = 0;
	int attrUnder, lastAttrUnder = 0;
	int palette[NALLCOLOURS];
	int numcolours;

	get_unitab(CP_ACP, unitab, 0);

	rtfsize = 100 + strlen(wnd->cfg.font.name);
	rtf = memallocn(rtfsize, char);
	rtflen = sprintf(rtf, "{\\rtf1\\ansi\\deff0{\\fonttbl\\f0\\fmodern %s;}\\f0\\fs%d",
			 wnd->cfg.font.name, wnd->cfg.font.height*2);

	/*
	 * Add colour palette
	 * {\colortbl ;\red255\green0\blue0;\red0\green0\blue128;}
	 */

	/*
	 * First - Determine all wnd->colours in use
	 *    o  Foregound and background wnd->colours share the same palette
	 */
	if (attr) {
	    memset(palette, 0, sizeof(palette));
	    for (i = 0; i < (len-1); i++) {
		fgcolour = ((attr[i] & ATTR_FGMASK) >> ATTR_FGSHIFT);
		bgcolour = ((attr[i] & ATTR_BGMASK) >> ATTR_BGSHIFT);

		if (attr[i] & ATTR_REVERSE) {
		    int tmpcolour = fgcolour;	/* Swap foreground and background */
		    fgcolour = bgcolour;
		    bgcolour = tmpcolour;
		}

		if (wnd->bold_mode == window_tag::BOLD_COLOURS && (attr[i] & ATTR_BOLD)) {
		    if (fgcolour  <   8)	/* ANSI wnd->colours */
			fgcolour +=   8;
		    else if (fgcolour >= 256)	/* Default wnd->colours */
			fgcolour ++;
		}

		if (attr[i] & ATTR_BLINK) {
		    if (bgcolour  <   8)	/* ANSI wnd->colours */
			bgcolour +=   8;
    		    else if (bgcolour >= 256)	/* Default wnd->colours */
			bgcolour ++;
		}

		palette[fgcolour]++;
		palette[bgcolour]++;
	    }

	    /*
	     * Next - Create a reduced palette
	     */
	    numcolours = 0;
	    for (i = 0; i < NALLCOLOURS; i++) {
		if (palette[i] != 0)
		    palette[i]  = ++numcolours;
	    }

	    /*
	     * Finally - Write the colour table
	     */
	    rtf = memrealloc(rtf, rtfsize + (numcolours * 25), char);
	    strcat(rtf, "{\\colortbl ;");
	    rtflen = strlen(rtf);

	    for (i = 0; i < NALLCOLOURS; i++) {
		if (palette[i] != 0) {
		    rtflen += sprintf(&rtf[rtflen], "\\red%d\\green%d\\blue%d;", wnd->defpal[i].rgbtRed, wnd->defpal[i].rgbtGreen, wnd->defpal[i].rgbtBlue);
		}
	    }
	    strcpy(&rtf[rtflen], "}");
	    rtflen ++;
	}

	/*
	 * We want to construct a piece of RTF that specifies the
	 * same Unicode text. To do this we will read back in
	 * parallel from the Unicode data in `udata' and the
	 * non-Unicode data in `tdata'. For each character in
	 * `tdata' which becomes the right thing in `udata' when
	 * looked up in `unitab', we just copy straight over from
	 * tdata. For each one that doesn't, we must WCToMB it
	 * individually and produce a \u escape sequence.
	 * 
	 * It would probably be more robust to just bite the bullet
	 * and WCToMB each individual Unicode character one by one,
	 * then MBToWC each one back to see if it was an accurate
	 * translation; but that strikes me as a horrifying number
	 * of Windows API calls so I want to see if this faster way
	 * will work. If it screws up badly we can always revert to
	 * the simple and slow way.
	 */
	while (tindex < len2 && uindex < len &&
	       tdata[tindex] && udata[uindex]) {
	    if (tindex + 1 < len2 &&
		tdata[tindex] == '\r' &&
		tdata[tindex+1] == '\n') {
		tindex++;
		uindex++;
            }

            /*
             * Set text attributes
             */
            if (attr) {
                if (rtfsize < rtflen + 64) {
		    rtfsize = rtflen + 512;
		    rtf = memrealloc(rtf, rtfsize, char);
                }

                /*
                 * Determine foreground and background wnd->colours
                 */
                fgcolour = ((attr[tindex] & ATTR_FGMASK) >> ATTR_FGSHIFT);
                bgcolour = ((attr[tindex] & ATTR_BGMASK) >> ATTR_BGSHIFT);

		if (attr[tindex] & ATTR_REVERSE) {
		    int tmpcolour = fgcolour;	    /* Swap foreground and background */
		    fgcolour = bgcolour;
		    bgcolour = tmpcolour;
		}

		if (wnd->bold_mode == window_tag::BOLD_COLOURS && (attr[tindex] & ATTR_BOLD)) {
		    if (fgcolour  <   8)	    /* ANSI wnd->colours */
			fgcolour +=   8;
		    else if (fgcolour >= 256)	    /* Default wnd->colours */
			fgcolour ++;
                }

		if (attr[tindex] & ATTR_BLINK) {
		    if (bgcolour  <   8)	    /* ANSI wnd->colours */
			bgcolour +=   8;
		    else if (bgcolour >= 256)	    /* Default wnd->colours */
			bgcolour ++;
                }

                /*
                 * Collect other attributes
                 */
		if (wnd->bold_mode != window_tag::BOLD_COLOURS)
		    attrBold  = attr[tindex] & ATTR_BOLD;
		else
		    attrBold  = 0;
                
		attrUnder = attr[tindex] & ATTR_UNDER;

                /*
                 * Reverse video
		 *   o  If video isn't reversed, ignore colour attributes for default foregound
	         *	or background.
		 *   o  Special case where bolded text is displayed using the default foregound
		 *      and background wnd->colours - force to bolded RTF.
                 */
		if (!(attr[tindex] & ATTR_REVERSE)) {
		    if (bgcolour >= 256)	    /* Default color */
			bgcolour  = -1;		    /* No coloring */

		    if (fgcolour >= 256) {	    /* Default colour */
				if (wnd->bold_mode == window_tag::BOLD_COLOURS && (fgcolour & 1) && bgcolour == -1)
			    attrBold = ATTR_BOLD;   /* Emphasize text with bold attribute */

			fgcolour  = -1;		    /* No coloring */
		    }
		}

                /*
                 * Write RTF text attributes
                 */
		if (lastfgcolour != fgcolour) {
                    lastfgcolour  = fgcolour;
		    rtflen       += sprintf(&rtf[rtflen], "\\cf%d ", (fgcolour >= 0) ? palette[fgcolour] : 0);
                }

                if (lastbgcolour != bgcolour) {
                    lastbgcolour  = bgcolour;
                    rtflen       += sprintf(&rtf[rtflen], "\\highlight%d ", (bgcolour >= 0) ? palette[bgcolour] : 0);
                }

		if (lastAttrBold != attrBold) {
		    lastAttrBold  = attrBold;
		    rtflen       += sprintf(&rtf[rtflen], "%s", attrBold ? "\\b " : "\\b0 ");
		}

                if (lastAttrUnder != attrUnder) {
                    lastAttrUnder  = attrUnder;
                    rtflen        += sprintf(&rtf[rtflen], "%s", attrUnder ? "\\ul " : "\\ulnone ");
                }
	    }

	    if (unitab[tdata[tindex]] == udata[uindex]) {
		multilen = 1;
		before[0] = '\0';
		after[0] = '\0';
		blen = alen = 0;
	    } else {
		multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
					       NULL, 0, NULL, NULL);
		if (multilen != 1) {
		    blen = sprintf(before, "{\\uc%d\\u%d", multilen,
				   udata[uindex]);
		    alen = 1; strcpy(after, "}");
		} else {
		    blen = sprintf(before, "\\u%d", udata[uindex]);
		    alen = 0; after[0] = '\0';
		}
	    }
	    assert(tindex + multilen <= len2);
	    totallen = blen + alen;
	    for (i = 0; i < multilen; i++) {
		if (tdata[tindex+i] == '\\' ||
		    tdata[tindex+i] == '{' ||
		    tdata[tindex+i] == '}')
		    totallen += 2;
		else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
		    totallen += 6;     /* \par\r\n */
		else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
		    totallen += 4;
		else
		    totallen++;
	    }

	    if (rtfsize < rtflen + totallen + 3) {
		rtfsize = rtflen + totallen + 512;
		rtf = memrealloc(rtf, rtfsize, char);
	    }

	    strcpy(rtf + rtflen, before); rtflen += blen;
	    for (i = 0; i < multilen; i++) {
		if (tdata[tindex+i] == '\\' ||
		    tdata[tindex+i] == '{' ||
		    tdata[tindex+i] == '}') {
		    rtf[rtflen++] = '\\';
		    rtf[rtflen++] = tdata[tindex+i];
		} else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
		    rtflen += sprintf(rtf+rtflen, "\\par\r\n");
		} else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
		    rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
		} else {
		    rtf[rtflen++] = tdata[tindex+i];
		}
	    }
	    strcpy(rtf + rtflen, after); rtflen += alen;

	    tindex += multilen;
	    uindex++;
	}

        rtf[rtflen++] = '}';	       /* Terminate RTF stream */
        rtf[rtflen++] = '\0';
        rtf[rtflen++] = '\0';

	clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
	if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
	    memcpy(lock3, rtf, rtflen);
	    GlobalUnlock(clipdata3);
	}
	memfree(rtf);
    } else
	clipdata3 = NULL;

    GlobalUnlock(clipdata);
    GlobalUnlock(clipdata2);

    if (!must_deselect)
	SendMessage(wnd->hwnd, WM_IGNORE_CLIP, TRUE, 0);

    if (OpenClipboard(wnd->hwnd)) {
	EmptyClipboard();
	SetClipboardData(CF_UNICODETEXT, clipdata);
	SetClipboardData(CF_TEXT, clipdata2);
	if (clipdata3)
	    SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
	CloseClipboard();
    } else {
	GlobalFree(clipdata);
	GlobalFree(clipdata2);
    }

    if (!must_deselect)
	SendMessage(wnd->hwnd, WM_IGNORE_CLIP, FALSE, 0);
}

void get_clip(SshWindow wnd, wchar_t ** p, int *len)
{
    static HGLOBAL clipdata = NULL;
    static wchar_t *converted = 0;
    wchar_t *p2;

    if (converted) {
	memfree(converted);
	converted = 0;
    }
    if (!p) {
	if (clipdata)
	    GlobalUnlock(clipdata);
	clipdata = NULL;
	return;
    } else if (OpenClipboard(NULL)) {
	if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
	    CloseClipboard();
	    *p = (wchar_t*)GlobalLock(clipdata);
	    if (*p) {
		for (p2 = *p; *p2; p2++);
		*len = p2 - *p;
		return;
	    }
	} else if ( (clipdata = GetClipboardData(CF_TEXT)) ) {
	    char *s;
	    int i;
	    CloseClipboard();
	    s = (char*)GlobalLock(clipdata);
	    i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
	    *p = converted = memallocn(i, wchar_t);
	    MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, converted, i);
	    *len = i - 1;
	    return;
	} else
	    CloseClipboard();
    }

    *p = NULL;
    *len = 0;
}

/*
 * Print a message box and perform a fatal exit.
 */
void fatalbox(SshWindow wnd, char *fmt, ...)
{
    va_list ap;
    char *stuff, morestuff[100];

    va_start(ap, fmt);
    stuff = dupvprintf(fmt, ap);
    va_end(ap);
    sprintf(morestuff, "Fatal Error");
    MessageBoxA(wnd->hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
    memfree(stuff);
    PostQuitMessage(1);
}

/*
 * Print a modal (Really Bad) message box and perform a fatal exit.
 */
void modalfatalbox(SshWindow wnd, char *fmt, ...)
{
    va_list ap;
    char *stuff, morestuff[100];

    va_start(ap, fmt);
    stuff = dupvprintf(fmt, ap);
    va_end(ap);
    sprintf(morestuff, "Fatal Error");
    MessageBoxA(wnd->hwnd, stuff, morestuff,
	       MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
    memfree(stuff);
    PostQuitMessage(1);
}

typedef BOOL (WINAPI *p_FlashWindowEx_t)(PFLASHWINFO);
static p_FlashWindowEx_t p_FlashWindowEx = NULL;

static void init_flashwindow(void)
{
	if (p_FlashWindowEx) return;
    HMODULE user32_module = LoadLibrary(L"USER32.DLL");
    if (user32_module) {
	p_FlashWindowEx = (p_FlashWindowEx_t)
	    GetProcAddress(user32_module, "FlashWindowEx");
    }
}

static BOOL flash_window_ex(SshWindow wnd, DWORD dwFlags, UINT uCount, DWORD dwTimeout)
{
    if (p_FlashWindowEx) {
	FLASHWINFO fi;
	fi.cbSize = sizeof(fi);
	fi.hwnd = wnd->hwnd;
	fi.dwFlags = dwFlags;
	fi.uCount = uCount;
	fi.dwTimeout = dwTimeout;
	return (*p_FlashWindowEx)(&fi);
    }
    else
	return FALSE; /* shrug */
}

/*
 * Timer for platforms where we must maintain window flashing manually
 * (e.g., Win95).
 */
static void flash_window_timer(void *ctx, long now, HWND hwnd)
{
	SshWindow wnd=(SshWindow)ctx;
    if (wnd->flashing && now - wnd->next_flash >= 0) {
	flash_window(wnd, 1);
    }
}

/*
 * Manage window caption / taskbar flashing, if enabled.
 * 0 = stop, 1 = maintain, 2 = start
 */
static void flash_window(SshWindow wnd, int mode)
{
    if ((mode == 0) || (wnd->cfg.beep_ind == B_IND_DISABLED)) {
	/* stop */
	if (wnd->flashing) {
	    wnd->flashing = 0;
	    if (p_FlashWindowEx)
		flash_window_ex(wnd, FLASHW_STOP, 0, 0);
	    else
		FlashWindow(wnd->hwnd, FALSE);
	}

    } else if (mode == 2) {
	/* start */
	if (!wnd->flashing) {
	    wnd->flashing = 1;
	    if (p_FlashWindowEx) {
		/* For so-called "steady" mode, we use uCount=2, which
		 * seems to be the traditional number of flashes used
		 * by user notifications (e.g., by Explorer).
		 * uCount=0 appears to enable continuous flashing, per
		 * "flashing" mode, although I haven't seen this
		 * documented. */
		flash_window_ex(wnd, FLASHW_ALL | FLASHW_TIMER,
				(wnd->cfg.beep_ind == B_IND_FLASH ? 0 : 2),
				0 /* system cursor blink rate */);
		/* No need to schedule timer */
	    } else {
		FlashWindow(wnd->hwnd, TRUE);
		wnd->next_flash = schedule_timer(450, flash_window_timer, wnd, wnd->hwnd);
	    }
	}

    } else if ((mode == 1) && (wnd->cfg.beep_ind == B_IND_FLASH)) {
	/* maintain */
	if (wnd->flashing && !p_FlashWindowEx) {
	    FlashWindow(wnd->hwnd, TRUE);	/* toggle */
	    wnd->next_flash = schedule_timer(450, flash_window_timer, wnd, wnd->hwnd);
	}
    }
}

/*
 * Beep.
 */
void do_beep(SshWindow wnd, int mode)
{
    if (mode == BELL_DEFAULT) {
	/*
	 * For MessageBeep style bells, we want to be careful of
	 * timing, because they don't have the nice property of
	 * PlaySound bells that each one cancels the previous
	 * active one. So we limit the rate to one per 50ms or so.
	 */
	static long lastbeep = 0;
	long beepdiff;

	beepdiff = GetTickCount() - lastbeep;
	if (beepdiff >= 0 && beepdiff < 50)
	    return;
	MessageBeep(MB_OK);
	/*
	 * The above MessageBeep call takes time, so we record the
	 * time _after_ it finishes rather than before it starts.
	 */
	lastbeep = GetTickCount();
    } else if (mode == BELL_WAVEFILE) {
	if (!PlaySoundA(wnd->cfg.bell_wavefile.path, NULL,
		       SND_ASYNC | SND_FILENAME)) {
	    char buf[sizeof(wnd->cfg.bell_wavefile.path) + 80];
	    char otherbuf[100];
	    sprintf(buf, "Unable to play sound file\n%s\n"
		    "Using default sound instead", wnd->cfg.bell_wavefile.path);
	    sprintf(otherbuf, "Sound Error");
	    MessageBoxA(wnd->hwnd, buf, otherbuf,
		       MB_OK | MB_ICONEXCLAMATION);
	    wnd->cfg.beep = BELL_DEFAULT;
	}
    } else if (mode == BELL_PCSPEAKER) {
	static long lastbeep = 0;
	long beepdiff;

	beepdiff = GetTickCount() - lastbeep;
	if (beepdiff >= 0 && beepdiff < 50)
	    return;

	/*
	 * We must beep in different ways depending on whether this
	 * is a 95-series or NT-series OS.
	 */
	if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
	    Beep(800, 100);
	else
	    MessageBeep(-1);
	lastbeep = GetTickCount();
    }
    /* Otherwise, either visual bell or disabled; do nothing here */
    if (!wnd->term->has_focus) {
	flash_window(wnd, 2);	       /* start */
    }
}

/*
 * Minimise or restore the window in response to a server-side
 * request.
 */
void set_iconic(SshWindow wnd, int iconic)
{
    if (IsIconic(wnd->hwnd)) {
	if (!iconic)
	    ShowWindow(wnd->hwnd, SW_RESTORE);
    } else {
	if (iconic)
	    ShowWindow(wnd->hwnd, SW_MINIMIZE);
    }
}

/*
 * Move the window in response to a server-side request.
 */
void move_window(SshWindow wnd, int x, int y)
{
    if (wnd->cfg.resize_action == RESIZE_DISABLED || 
        wnd->cfg.resize_action == RESIZE_FONT ||
	IsZoomed(wnd->hwnd))
       return;

    SetWindowPos(wnd->hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
}

/*
 * Move the window to the top or bottom of the z-order in response
 * to a server-side request.
 */
void set_zorder(SshWindow wnd, int top)
{
    if (wnd->cfg.alwaysontop)
	return;			       /* ignore */
    SetWindowPos(wnd->hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
		 SWP_NOMOVE | SWP_NOSIZE);
}

/*
 * Refresh the window in response to a server-side request.
 */
void refresh_window(SshWindow wnd)
{
    InvalidateRect(wnd->hwnd, NULL, TRUE);
}

/*
 * Maximise or restore the window in response to a server-side
 * request.
 */
void set_zoomed(SshWindow wnd, int zoomed)
{
    if (IsZoomed(wnd->hwnd)) {
        if (!zoomed)
	    ShowWindow(wnd->hwnd, SW_RESTORE);
    } else {
	if (zoomed)
	    ShowWindow(wnd->hwnd, SW_MAXIMIZE);
    }
}

/*
 * Report whether the window is iconic, for terminal reports.
 */
int is_iconic(SshWindow wnd)
{
    return IsIconic(wnd->hwnd);
}

/*
 * Report the window's position, for terminal reports.
 */
void get_window_pos(SshWindow wnd, int *x, int *y)
{
    RECT r;
    GetWindowRect(wnd->hwnd, &r);
    *x = r.left;
    *y = r.top;
}

/*
 * Report the window's pixel size, for terminal reports.
 */
void get_window_pixels(SshWindow wnd, int *x, int *y)
{
    RECT r;
    GetWindowRect(wnd->hwnd, &r);
    *x = r.right - r.left;
    *y = r.bottom - r.top;
}

/*
 * Return the window or icon title.
 */
char *get_window_title(SshWindow wnd, int icon)
{
    return icon ? wnd->icon_name : wnd->window_name;
}

/*
 * See if we're in full-screen mode.
 */
static int is_full_screen(SshWindow wnd)
{
    if (!IsZoomed(wnd->hwnd))
	return FALSE;
    if (GetWindowLongPtr(wnd->hwnd, GWL_STYLE) & WS_CAPTION)
	return FALSE;
    return TRUE;
}

/* Get the rect/size of a full screen window using the nearest available
 * monitor in multimon systems; default to something sensible if only
 * one monitor is present. */
static int get_fullscreen_rect(SshWindow wnd, RECT * ss)
{
#if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
	HMONITOR mon;
	MONITORINFO mi;
	mon = MonitorFromWindow(wnd->hwnd, MONITOR_DEFAULTTONEAREST);
	mi.cbSize = sizeof(mi);
	GetMonitorInfo(mon, &mi);

	/* structure copy */
	*ss = mi.rcMonitor;
	return TRUE;
#else
/* could also use code like this:
	ss->left = ss->top = 0;
	ss->right = GetSystemMetrics(SM_CXSCREEN);
	ss->bottom = GetSystemMetrics(SM_CYSCREEN);
*/ 
	return GetClientRect(GetDesktopWindow(), ss);
#endif
}


/*
 * Go full-screen. This should only be called when we are already
 * maximised.
 */
static void make_full_screen(SshWindow wnd)
{
    DWORD style;
	RECT ss;

    assert(IsZoomed(wnd->hwnd));

	if (is_full_screen(wnd))
		return;
	
    /* Remove the window furniture. */
    style = GetWindowLongPtr(wnd->hwnd, GWL_STYLE);
    style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
    if (wnd->cfg.scrollbar_in_fullscreen)
	style |= WS_VSCROLL;
    else
	style &= ~WS_VSCROLL;
    SetWindowLongPtr(wnd->hwnd, GWL_STYLE, style);

    /* Resize ourselves to exactly cover the nearest monitor. */
	get_fullscreen_rect(wnd, &ss);
    SetWindowPos(wnd->hwnd, HWND_TOP, ss.left, ss.top,
			ss.right - ss.left,
			ss.bottom - ss.top,
			SWP_FRAMECHANGED);

    /* We may have changed size as a result */

    reset_window(wnd,0);

}

/*
 * Clear the full-screen attributes.
 */
static void clear_full_screen(SshWindow wnd)
{
    DWORD oldstyle, style;

    /* Reinstate the window furniture. */
    style = oldstyle = GetWindowLongPtr(wnd->hwnd, GWL_STYLE);
    style |= WS_CAPTION | WS_BORDER;
    if (wnd->cfg.resize_action == RESIZE_DISABLED)
        style &= ~WS_THICKFRAME;
    else
        style |= WS_THICKFRAME;
    if (wnd->cfg.scrollbar)
	style |= WS_VSCROLL;
    else
	style &= ~WS_VSCROLL;
    if (style != oldstyle) {
	SetWindowLongPtr(wnd->hwnd, GWL_STYLE, style);
	SetWindowPos(wnd->hwnd, NULL, 0, 0, 0, 0,
		     SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
		     SWP_FRAMECHANGED);
    }

}

/*
 * Toggle full-screen mode.
 */
static void flip_full_screen(SshWindow wnd)
{
    if (is_full_screen(wnd)) {
	ShowWindow(wnd->hwnd, SW_RESTORE);
    } else if (IsZoomed(wnd->hwnd)) {
	make_full_screen(wnd);
    } else {
	SendMessage(wnd->hwnd, WM_FULLSCR_ON_MAX, 0, 0);
	ShowWindow(wnd->hwnd, SW_MAXIMIZE);
    }
}

